这几天忙着整理实验数据,耽搁了。数组部分已经写完了,加起来一共 10 道题吧,不算太难,接下来是链表部分,这是第一篇,包括 4 道题:Linked List Cycle,Linked List Cycle II,Intersection of Two Linked Lists,Remove Nth Node From End of List。另外,我决定用 C++ 来写后面的题,C 还是太原始了。
前两题挺有意思的,去年也写过,还记得当时写得非常痛苦,后来直接放弃了刷题计划……现在看来也不过如此,现在面临的任何问题几乎都有对应的解决方法,当时我太过自卑自傲,不愿去查找,现在好了,抱着学习的心态,想不出来就去查,学会别人的方法就好。应用双指针技术可以很好地解决这两个问题,第二题的解法叫 Floyd 算法,还挺有名的,自己画画图、设几个未知数就能把问题解决了。
Linked List Cycle
Given
head
, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following thenext
pointer. Internally,pos
is used to denote the index of the node that tail’snext
pointer is connected to. Note thatpos
is not passed as a parameter. Returntrue
if there is a cycle in the linked list. Otherwise, returnfalse
.
example:
1 | Input: head = [3,2,0,-4], pos = 1 |
solution:
1 | bool hasCycle(ListNode *head) { |
Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter. Notice that you should not modify the linked list.
example:
1 | Input: head = [3,2,0,-4], pos = 1 |
solution:
1 | ListNode *detectCycle(ListNode *head) { |
Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
example:
For example, the following two linked lists begin to intersect at node c1.
solution:
1 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { |
Remove Nth Node From End of List
Given the head
of a linked list, remove the nth
node from the end of the list and return its head. Follow up: Could you do this in one pass?
example:
1 | Input: head = [1,2,3,4,5], n = 2 |
solution:
1 | ListNode* removeNthFromEnd(ListNode* head, int n) { |
Summary: Two-pointer in Linked List
下面给出一个链表中双指针技巧的使用模板(来自leetcode)。
1 | // Initialize slow & fast pointers |
这就是全部的双指针技巧部分了,这几道题都不算难,解题思路也很直观,不多做分析了。