LeetCode:143. 重排链表
Posted 南岸青栀*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:143. 重排链表相关的知识,希望对你有一定的参考价值。
143. 重排链表
法1:借助列表存储节点对象
# 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: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
#借用列表,实现重排链表
lst = []
p = head
while p:
lst.append(p)
p = p.next
p = head
print((len(lst))//2)
for i in range((len(lst)-1)//2):
lst[len(lst)-i-1].next = lst[i+1]
lst[i].next = lst[len(lst)-1-i]
lst[len(lst)-i-2].next = None
法2:
# 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: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
#找到中点
pre,slow = head,head
while pre and pre.next:
pre = pre.next.next
slow = slow.next
mid = slow.next
slow.next = None
#反转后半段
head2 = None
while mid:
temp = mid.next
mid.next = head2
head2,mid = mid,temp
#拼接
while head2:
tmp1 = head.next
tmp2 = head2.next
head.next = head2
head2.next = tmp1
head,head2 = tmp1,tmp2
以上是关于LeetCode:143. 重排链表的主要内容,如果未能解决你的问题,请参考以下文章