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))
相关文章推荐
- [leetcode] 92. Reverse Linked List II
- 【leetcode】92. Reverse Linked List II
- [leetcode] 【链表】92. Reverse Linked List II
- leetcode题解-92. Reverse Linked List II
- [LeetCode] 92. Reverse Linked List II
- leetcode 92. Reverse Linked List II
- [Leetcode]@python 92. Reverse Linked List II
- leetcode 92. Reverse Linked List II 反转链表 + 头插入反转链表(或者使用栈)
- 【LeetCode】92. Reverse Linked List II
- [LeetCode] 92. Reverse Linked List II
- LeetCode 92. Reverse Linked List II ***** 虚拟头结点
- Leetcode 92. Reverse Linked List II
- LeetCode92. Reverse Linked List II
- [leetcode] 92. Reverse Linked List II 解题报告
- [LeetCode]92. Reverse Linked List II
- leetcode 25. Reverse Nodes in k-Group & leetcode 92. Reverse Linked List II
- 【leetcode】92. Reverse Linked List II
- LeetCode 92. Reverse Linked List II
- leetcode 92. Reverse Linked List II
- LeetCode 92. Reverse Linked List II 解题报告