2. Linked List
好题
Reverse Nodes in k-Group
Insert into a sorted circular linked list
Flatten a Multilevel doubly linked list
LRU Cache
Reverse Linked List
Iterative & recursive solution 都需要掌握
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next= head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
//recursive
public ListNode reverseListRecursive(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseListRecursive(head.next);
head.next.next = head;
head.next = null;
return newHead;
}Remove duplicates from sorted list II
[1,2,2,4,4,5] -> [1,5]
[1,1,2] ->[2]
[1,2,2] ->[1]
Remove Nth Node from End of List
slow, fast pointer
Swap Nodes in Pairs
reverse Nodes in K-Group, k = 2的情况
需要掌握both recursive and iterative approach
Iterative solution
Reverse Nodes in k-Group
Swap nodes in pairs的general solution
split list into 2 parts, first k nodes and rest
if list.size() < k, return original list
else: reverse first K nodes and recursively reverseKGroup for the rest of nodes
Iterative solution
Reorder List
基础题,适合拿来练手
3步走
fast, slow指针找mid
reverse seond Half
merge 2 lists
Insert into a sorted circular linked list
好题
首先分成两种情况,head 是否为空
如果head不为空的话,先找到max和min
然后分两种情况讨论
insertVal >= max || insertVal <= min
insertVal在min和max之间
这题要注意避免死循环的情况
Flatten a Multilevel doubly linked list
好题
建立一个flattenTail函数,return tail node
然后分5种情况讨论
head is empty
no child, no next
next, no child
child, no next
child and next
LRU Cache
initial solution
doubly linked list + hashmap
key is key, value is Node
follow up, what if only single list is allowed?
single list + hashmap
key is key, value is prevNode
Doubly list + HashMap
Single list + HashMap
Last updated
Was this helpful?