您的位置:首页 > 其它

leetcode: 92. Reverse Linked List II

2017-11-22 10:22 363 查看

Problem

# Reverse a linked list from position m to n. Do it in-place and in one-pass.
#
# For example:
# Given 1->2->3->4->5->NULL, m = 2 and n = 4,
#
# return 1->4->3->2->5->NULL.
#
# Note:
# Given m, n satisfy the following condition:
# 1 ≤ m ≤ n ≤ length of list.


AC

class ListNode():
def __init__(self, x):
self.val = x
self.next = None

class Solution():
def reverseBetween(self, head, m, n):
if m==n:
return head
idx = 1
h = None
p = head
vals = []
while True:
if idx==m:
h = p
if idx>=m and idx<=n:
vals.append(p.val)
if idx==n:
break
idx = idx +1
p = p.next
while h!=p.next:
h.val = vals.pop()
h = h.next
return head

class ListNode():
def __init__(self, x):
self.val = x
self.next = None

class Solution():
def reverseBetween(self, head, m, n):
diff, dummy, cur = n - m + 1, ListNode(-1), head
dummy.next = head
last_unswapped = dummy
while cur and m > 1:
cur, last_unswapped, m = cur.next, cur, m - 1
prev, first_swapped = last_unswapped,  cur
while cur and diff > 0:
cur.next, prev, cur, diff = prev, cur, cur.next, diff - 1
last_unswapped.next, first_swapped.next = prev, cur
return dummy.next

if __name__ == "__main__":
head, head.next, head.next.next, head.next.next.next, head.next.next.next.next \
= ListNode(1), ListNode(2), ListNode(3), ListNode(4), ListNode(5)
print(Solution().reverseBetween(head, 2, 4))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: