Leetcode ---- 143.重排链表

题目:

给定一个单链表 LL0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→LnL1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

思路:

这道题需要做的就是将倒数第n个插入第n个元素的后面。

我第一反应就是用栈。首先将链表推入栈中,也得到中间值。然后逐个退出插入初始链表中即可。

第二个做法是用快慢指针。得到慢指针的位置后反转链表,再相互插入即可。

注意 最开始用栈操作出现阻碍,缘由就是重组链表后,最后的元素没有指向null!

程序:

/**
 * 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)
            return ;
        else if (!head->next)
            return;
        int num = 0;
        stack<ListNode *> stk;
        ListNode *p = head,*tmp;
        while (p != nullptr){
            stk.push(p);
            p = p->next;
            num++;
        }
        p = head;
        num = num/2;
        while (num-- >= 0){
            tmp = p->next;
            p->next = stk.top();
            p->next->next = tmp;
            p = p->next->next;
            stk.pop();
        }
        p->next = nullptr;  // importance
        return;
        
   /*     if (!head)
            return;
        ListNode *slow = head,*fast = head;
        while (fast != nullptr && fast->next != nullptr){
            slow = slow->next;   
            fast = fast->next->next;
        }
        
        ListNode *p = head;
        fast = reverseList(slow);
        while (fast != nullptr && p->next != nullptr){
            auto tmp = p->next;
            p->next = fast;
            fast = fast->next;
            p->next->next = tmp;
            p = p->next->next;
        }
        p->next = NULL;*/
                    
    }
    
    ListNode* reverseList(ListNode* _head) {
        
        if(_head == NULL||_head->next == NULL){
            return _head;
        }
        
        ListNode *ans = reverseList(_head->next);
        _head->next->next = _head;
        _head->next = NULL;
        return ans; 
    }
    
};

猜你喜欢

转载自blog.csdn.net/hc372893308/article/details/83830614