2/5/2018
Amazon Questions 5题easy Linked List
206 Reverse Linked List Use current, prev and next to reverse while(current != null){ next = current.next; current.next = prev; prev = current; current = next; } Time: O(n), Space: O(1)
21 Merge Two Sorted Lists Create a extra node for the head of the merged list Time: O(n), Space: O(1)
141 Linked List Cycle Two pointers while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(fast == slow){ return true; } } Time: O(n), Space: O(1)
234 Palindrome Linked List Get the length of the linked list, split in half, reverse the second half, compare with the first to see if the lists are identical Time: O(n), Space: O(1)
160 Intersection of Two Linked Lists Solution 1: Get the length of both linked lists, if different, move the start pointer forward to the same length, check if the node are the same node Solution 2: Iterate both linked lists, so the total length should be the same For the end of first iteration, we just reset the pointer to the head of another linked list For the second iteration, the pace is the same, as they are the same length and compare the node and find the intersection If no intersection, after iterating both list and it will stop at null. Time: O(n), Space: O(1)
|