您的位置:首页 > 编程语言 > Python开发

leetcode 【 Reorder List 】python 实现

2015-01-09 23:19 543 查看
题目:

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given
{1,2,3,4}
, reorder it to
{1,4,2,3}
.

代码: oj 测试通过 248 ms

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
# @param head, a ListNode
# @return nothing
def reorderList(self, head):
if head is None or head.next is None or head.next.next is None:
return head

dummyhead = ListNode(0)
dummyhead.next = head

# get the length of the linked list
p = head
list_length = 0
while p is not None:
list_length += 1
p = p.next

#reverse the second half linked list
fast = dummyhead
for i in range((list_length+1)/2):
fast = fast.next
pre = fast
curr = pre.next
for i in range( (list_length)/2 - 1 ):
tmp = curr.next
curr.next = tmp.next
tmp.next = pre.next
pre.next = tmp

#merge
h2 = pre.next
fast.next = None # cut the connection between 1st half linked list and 2nd half linked list
while head is not None and h2 is not None:
tmp = head.next
head.next = h2
tmp2 = h2.next
head.next.next = tmp
h2 = tmp2
head = tmp

return dummyhead.next


思路

这道题的路子分三块:

1. 遍历单链表 求链表长度

2. 锁定后半个链表,反转后半个链表的每个元素

3. 切断前后半个链表的链接处 然后合并两个链表
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: