leetcode系列-重排链表(超级经典系列)

分类:链表

难度:medium

涉及内容:翻转链表、快慢指针确定中点等

  1. 重排链表

给定一个单链表 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.

题解

这个题目有清楚的三步

第一步 找到中点,分为左右两个链表

使用快慢指针,快指针每次走两步,慢指针每次走一步,前面加入一个新的节点,要不然最终的结果会偏后一步

 newnode = ListNode(-1)
        newnode.next = head
        slow,fast = newnode,newnode
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        right = slow.next
        slow.next = None
        left = head

第二步 翻转右链表

最基础的翻转链表题目呀,一定要记住哇,每次都忘。。。

def reverse_linked_list(head):
            prev = None
            cur = head
            while cur:
                tmp = cur.next
                cur.next = prev
                prev = cur
                cur = tmp
            return prev

第三步 依次合并

这一步就很简单没有什么说的,依次添加即可

代码

完整代码

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

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: None Do not return anything, modify head in-place instead.
        """
        def reverse_linked_list(head):
            prev = None
            cur = head
            while cur:
                tmp = cur.next
                cur.next = prev
                prev = cur
                cur = tmp
            return prev
        # middle node
        newnode = ListNode(-1)
        newnode.next = head
        slow,fast = newnode,newnode
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        right = slow.next
        slow.next = None
        left = head
        
        # reverse right linkedlist
        right = reverse_linked_list(right)
        # merge
        new=pos= ListNode(-1)
        leftcur,rightcur=head,right
        while leftcur and rightcur:
            pos.next = leftcur
            leftcur = leftcur.next
            pos = pos.next
            pos.next = rightcur
            rightcur = rightcur.next
            pos = pos.next
        pos.next = None
        while leftcur:
            pos.next = leftcur
            leftcur = leftcur.next
            pos = pos.next
        while rightcur:
            pos.next = rightcur
            rightcur = rightcur.next
            pos = pos.next
        pos.next=None
        return new.next
发布了41 篇原创文章 · 获赞 0 · 访问量 6147

猜你喜欢

转载自blog.csdn.net/Yolo_C/article/details/105105288