本文共 1298 字,大约阅读时间需要 4 分钟。
这个题目的思想是比较巧妙的,拆解来看都是我们熟悉的三种基本的链表操作
1. 利用快慢指针将链表分为前后两部分(若总长为奇数,则前半部分多1) 2. 将后半部分链表进行翻转 3. 重新将链表连接在一起链表记得画图!
链表记得画图! 链表记得画图!# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ # 思路一开始就错了,自己是个太暴力的人,但是机器不应该这样 # 0个1个两个节点不需要进行这个操作 if head and head.next and head.next.next: # 将链表一分为二 fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next head1,head2 = head,slow.next slow.next = None # 翻转后半部分链表 dummy = ListNode(0) dummy.next = head2 p = head2.next head2.next = None while p: tmp,p = p,p.next tmp.next = dummy.next dummy.next = tmp head2 = dummy.next # 重新将两部分连接起来 p1 = head1; p2 = head2 while p2: tmp1 = p1.next; tmp2 = p2.next p1.next = p2; p2.next = tmp1 p1 = tmp1; p2 = tmp2