key points:
-simultaneous assignment
-dummy head node to thread linked lists
-use prev node to reverse linked list
# 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: void Do not return anything, modify head in-place instead.
"""
#divide the list into two halves, prev is the node before the starting node of second list
if head is None or head.next is None: return
slow,fast,prev=head,head,None
while fast and fast.next :
prev,slow,fast=slow,slow.next,fast.next.next
#reverse the second list
current,prev.next,prev=slow,None,None
while current:
current.next,prev,current=prev,current,current.next
#create a dummy head and thread two list one by one
l1,l2=head,prev
dummy=ListNode(0)
current=dummy
while l1!=None and l2!=None:
current.next,current,l1 =l1,l1,l1.next
current.next,current,l2 =l2,l2,l2.next
143. Reorder List
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it ...
- 一、题目 二、解题 把链表组成一个环状,1,2,3,4->1,4,2,3 定义两个方向的指针,第一个方向从头往后,...