题解 | #重排链表#

重排链表

https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode *head) {
        if(head == nullptr) return ;
        // 链表折叠? 
        // 1. 找到中间节点!
        // 2. 将链表断开,并后半段放入栈中!
        // 3. 依次弹出连接即可!
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* pre = nullptr;

        while(fast != nullptr){
            fast = fast->next;
            if(fast == nullptr) break;
            pre = slow;
            slow = slow->next;
            fast = fast->next;
        }

        if(slow == head) return; // 链表中 <=2 个元素!

        if(pre) pre->next = nullptr;
        
        ListNode* midHead = slow;

        stack<ListNode*> stk;

        while(midHead){
            stk.push(midHead);
            midHead = midHead->next;
        }

        ListNode* cur = head;
        ListNode* tmp;
        while(!stk.empty()){
            tmp = stk.top();
            stk.pop();
            tmp->next = cur->next;
            cur->next = tmp;
            cur = cur->next;
            if(cur->next) cur = cur->next;
        }
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务