2016-07-17更新:
142.Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
给定一个单链表,判断其是否带环,若带环返回环的入口结点,否则返回NULL.
判断是否带环,快慢指针法就可以解决问题。要返回环的入口,就显得比较麻烦了,首先,要进行一轮必要的推理。
1. 声明entry,fast,slow三个指针,均指向head结点
2. fast以slow的二倍速前进,当两者相等时,即说明链表带环,在此条件下,让entry出发,下面分析entry移动的终止条件。
设入口距头指针距离L1,fast,slow相遇点距入口距离L2,环长为C,容易得到fast,slow指针相遇条件是:fast前进距离-slow前进距离=N*C。而在相同时间内,fast指针前进距离是slow的两倍。所以有:
2 * (L1+L2) = L1 + L2 + n * C => L1 + L2 = n * C => L1 = (n - 1) C + (C - L2)
其中,C-L2是相遇点到入口的距离,L1是头指针到入口的距离,说明当slow到达相遇点时,entry开始前进,当slow和entry相等(这里可能是真的相等,也有可能是相差整数倍的环长)时,entry所指向的就是入口结点。 思路大致就是这样,代码请见我的github [Leetcode第142题](https://github.com/Kelvinmao/Leetcode/tree/master/LinkedList)
328.Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example: Given 1->2->3->4->5->NULL, return 1->3->5->2->4->NULL.
Note: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on …
给定一个单链表,将其位序为奇数的结点放在一起,跟在偶数结点的后面。
思路:将原链表拆成奇数链表和偶数链表,那么我们需要两个指针odd和even,顾名思义一个指向第一个结点,另一个指向第二个结点。那么之后的操作很简单,由于even的next指向一个奇数,所以:
odd->next=even->next;
odd=odd->next;
even指针的操作相同,不再赘述。
代码见我的github:
Leetcode第328题