给定一个单链表 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.
思路:1、创建一个空数组num,遍历链表并将链表的值放入数组中,然后根据数组的下标重新取值
2、(学长提供)先用快慢指针找到链表中点,然后对后半部分做链表逆序,最后把前后两段链表合并
第二种我有点不太行,便尝试了第一种
代码:
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head.next:
return head
num = []
while head is not None:
num.append(head)
head = head.next
count = len(num)
for i in range(count//2):
# print(num[i])
num[i].next = num[-1-i]
num[-1-i].next = num[i+1]
num[i+1].next = None
return num[0]
中间遇到的问题:一开始做的是count/2,这样很容易溢出,就改成了count//2(向下取整防止溢出)。另一个问题虽然不太懂是为什么,一开始我是这么写的
dummy = ListNode() dummy.next = head cur = dummy while cur is not None: num.append(cur) cur = cur.next
放上去一直会出现问题,后来直接用head就ok了。
和师兄讨论时想到的新方法:使用栈和队列做,一开始的步骤也是放到数组里,后面的操作是利用一个标识符pos=1,将第一个数放到栈,pos取反;第二个数放到队列,pos取反;第三个数放到栈,pos取反,以此类推,重构链表的时候直接按新链表的顺序取数即可,代码如下:
def reorderList(head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ num = [] while head: num.append(head.val) head = head.next pos = 1 head = ListNode(0) dummy = head # print(num) while num: # print(count) if pos: val = num.pop(0) # print(val) head.next = ListNode(val) else: val = num.pop(-1) # print(val) head.next = ListNode(val) print(head.val) head = head.next pos = bool(1 - pos) return dummy.next
但是这个方法在LeetCode上有问题,在自己的编译器上就没问题,目前还在和师兄讨论中www。
题目来自LeetCode第143题