给出一个链表,先判断链表是否带环,如果带环,求出环的入口。
判断是否带环:用快慢指针。快指针每走两步,慢指针走一步,如果两者在某个点处相
遇,则链表带环。
下边给出函数的实现代码:
typedef struct LinkNode { DataType data; struct LinkNode *next; }LinkNode,*pLinkNode; typedef struct LinkList { LinkNode *pHead; }LinkList,*pLinkList; pLinkNode isCircle(pLinkList plist) { assert(plist); if (NULL == plist->pHead) { printf("链表为空\n"); return NULL; } pLinkNode fast = plist->pHead; pLinkNode slow = plist->pHead; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; if (fast == slow) return fast; } return NULL; }
如果
如果链表带环,看下边的图:
代码:
pLinkNode firstCrossNode(pLinkList plist) { assert(plist); if (NULL == plist->pHead) { printf("链表是空\n"); return NULL; } pLinkNode ret = isCircle(plist); if (ret == NULL) { printf("链表不带环\n"); return NULL; } pLinkNode fast = plist->pHead; pLinkNode slow = ret; while (fast) { fast = fast->next; slow = slow->next; if (fast == slow) return fast; } }
时间: 2024-10-09 10:59:19