每日一题(143. 重排链表)-快慢指针/反转链表

题目

143. 重排链表

题解思路

  • 题目要求将L0 → L1 → … → Ln - 1 → Ln 排序的列表转换为
    • L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

首先

  1. 利用快慢指针,找到链表的中点位置
  2. 然后将链表的后半部分进行反转
  3. 将链表的前半部分以及反转后的后半部分进行依次拼接
  4. 即可得到题目要求的顺序

代码

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:

    void reorderList(ListNode* head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast != nullptr && fast->next != nullptr){
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* cur = slow->next;
        slow->next = nullptr;

        ListNode* pre = nullptr;
        while(cur){
            ListNode* nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }

        cur = head;
        while(pre != nullptr){
            ListNode *t = pre->next;
            pre->next = cur->next;
            cur->next = pre;
            cur = pre->next;
            pre = t;
        }
        
        
    }
};

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        def reverse(node):
            pre = None 
            cur = node 
            while cur:
                nxt = cur.next
                cur.next = pre
                pre = cur
                cur = nxt
            return pre
        pre = ListNode()

        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        mid = reverse(slow.next)
        slow.next = None
        cur = pre
        while head and mid:
            cur.next = head
            head = head.next
            cur = cur.next
            cur.next = mid
            mid = mid.next
            cur = cur.next
        cur.next = head if head else mid

你可能感兴趣的:(Leetcode每日一题,python,c++,快慢指针,链表反转)