typedef struct node { int num; struct node *next; } node; node *getLastNNode(node *head, int n) { node *pfirst = head; node *psecond = null; while (n-- > 0 && (pfirst != NULL)) { pfirst = pfirst->next; } if (pfirst != NULL) { psecond = head; } while (pfirst != NULL) { pfirst = pfirst->next; psecond = psecond->next; } return psecond; }
能否再优化一下这个时间复杂度呢?有一个很巧妙的方法:设置两个指针*search、*mid都指向单链表的头节点。其中* search的移动速度是*mid的2倍。当*search指向末尾节点的时候,mid正好就在中间了。
C源代码如下:
/* * c.c * * Created on: 2011-10-27 * Author: bjfuwangzhu */ #include<stdio.h> typedef struct node { int num; struct node *next; } node; void getMidNode(node *head) { node *search, *mid; mid = search = head; while (search->next != NULL) { //search移动的速度是 mid的2倍 if (search->next->next != NULL) { search = search->next->next; mid = mid->next; } else { search = search->next; } } }
另外,快慢指针在解决单链表环问题的时候是非常有用的,具体请参见《★经典问题—链表中的环问题 》
有一个单链表,其中可能有一个环,也就是某个节点的next指向的是链表中在它之前的节点,这样在链表的尾部形成一环。
问题:
1、如何判断一个链表是不是这类链表?
2、如果链表为存在环,如果找到环的入口点?
一、判断链表是否存在环,办法为:
设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。(当然,fast先行头到尾部为NULL,则为无环链表)程序如下:
/* * c.c * * Created on: 2011-10-27 * Author: bjfuwangzhu */ #include<stdio.h> typedef struct node { int num; struct node *next; } node; int isExitsLoop(node *head) { node *fast, *slow; fast = slow = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { break; } } return ((fast == NULL) || (fast->next == NULL)); }
二、找到环的入口点
当fast若与slow相遇时,slow肯定没有走遍历完链表,而fast已经在环内循环了n圈(1<=n)。假设slow走了s步,则fast走了2s步(fast步数还等于s 加上在环上多转的n圈),设环长为r,则:
2s = s + nr
s= nr
设整个链表长L,入口环与相遇点距离为x,起点到环入口点的距离为a。
a + x = nr
a + x = (n – 1)r +r = (n-1)r + L - a
a = (n-1)r + (L – a – x)
(L – a – x)为相遇点到环入口点的距离,由此可知,从链表头到环入口点等于(n-1)循环内环+相遇点到环入口点,于是我们从链表头、与相遇点分别设一个指针,每次各走一步,两个指针必定相遇,且相遇第一点为环入口点。程序描述如下:
#include<stdio.h> typedef struct node { int num; struct node *next; } node; node* findLoopPort(node *head) { node *fast, *slow; fast = slow = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { break; } } if ((fast == NULL) || (fast->next == NULL)) { return NULL; } slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return slow; }
扩展问题:
判断两个单链表是否相交,如果相交,给出相交的第一个点(两个链表都不存在环)。
比较好的方法有两个:
一、将其中一个链表首尾相连,检测另外一个链表是否存在环,如果存在,则两个链表相交,而检测出来的依赖环入口即为相交的第一个点。
二、如果两个链表相交,那个两个链表从相交点到链表结束都是相同的节点,我们可以先遍历一个链表,直到尾部,再遍历另外一个链表,如果也可以走到同样的结尾点,则两个链表相交。
这时我们记下两个链表length,再遍历一次,长链表节点先出发前进(lengthMax-lengthMin)步,之后两个链表同时前进,每次一步,相遇的第一点即为两个链表相交的第一个点。