LeetCode算法题143:重排链表解析

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→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.

这个题可以先用快慢指针找到中点保存,然后截断,将后半段存入栈中,然后遍历前半段,把栈中的元素插进链表,栈起到了翻转链表的作用。

C++源代码:

/**
 * 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;
        ListNode *slow=head, *fast=head;
        stack<ListNode*> s;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        fast = slow->next;
        slow->next = NULL;
        slow = head;
        while(fast){
            s.push(fast);
            fast = fast->next;
        }
        while(!s.empty()){
            ListNode *tmp = slow->next;
            slow->next = s.top();
            slow->next->next = tmp;
            slow = tmp;
            s.pop();
        }
        
    }
};

python3源代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if head==None:
            return
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        fast = slow.next
        slow.next = None
        slow = head
        s = []
        while fast:
            s.append(fast)
            fast = fast.next
        while len(s)!=0:
            tmp = slow.next
            slow.next = s.pop()
            slow.next.next = tmp
            slow = tmp
        

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/88075828