Reverse & Sorting Problem
25. Reverse Nodes in K-Group
Leetcode: https://leetcode.com/problems/reverse-nodes-in-k-group/description/
[Solution]
- Find
k + 1
th node - Use a stack to reverse k nodes
- Link the reversed part with
k + 1
th node - Recursively do above till head is null
1 | def reverseKGroup(self, head: ListNode, k: int) -> ListNode: |
92. Reverse Linked List II
Leetcode: https://leetcode.com/problems/reverse-linked-list-ii/
Note: Beware of cases when m = 1
1 | def reverseBetween(self, head, m, n): |
24. Swap Nodes in Pairs
Leetcode: https://leetcode.com/problems/swap-nodes-in-pairs/
1 | def swapPairs(self, head): |
138. Copy List with Random Pointer
Leetcode: https://leetcode.com/problems/copy-list-with-random-pointer/solution/
[Solution]:
- Use a
dict
to track visited nodes - If current node is in the visited
dict
, usevisited[node]
, else return a new copy of node
1 | class Solution(object): |
[Similar Problems]
- Clone Graph
86. Partition List
Leetcode: https://leetcode.com/problems/partition-list/
Note: Remember to set large.next = None
after the iteration. Or there might be cycle in the returned linked list!
1 | def partition(self, head: ListNode, x: int) -> ListNode: |
Stack with ordering
1019. Next Greater Node In Linked List
Leetcode: https://leetcode.com/problems/next-greater-node-in-linked-list/
Note:
- Use a stack, keep the stack with descending order
1 | def nextLargerNodes(self, head): |