LeetCode 143. 重排链表

2022-09-10  本文已影响0人  草莓桃子酪酪
题目

给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

例:
输入:head = [1,2,3,4]
输出:[1,4,2,3]

方法:翻转后半部分链表

思路同 234. 回文链表,区别在于本题在翻转链表后进行插入

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reorderList(self, head):
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        right = slow.next
        slow.next = None
        left = head
        right = self.reverse(right)

        while right:
            curLeft = left.next
            left.next = right
            left = curLeft

            curRight = right.next
            right.next = left
            right = curRight
        return head
    
    def reverse(self, node):
        pre = None
        while node:
            temp = node.next
            node.next = pre
            pre = node
            node = temp
        return pre
参考

代码相关:https://programmercarl.com/0143.%E9%87%8D%E6%8E%92%E9%93%BE%E8%A1%A8.html

上一篇下一篇

猜你喜欢

热点阅读