码迷,mamicode.com
首页 > 其他好文 > 详细

判断链表是否成环,如果成环返回成环的第一个结点

时间:2015-01-24 10:17:34      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>
typedef struct LinkNode
{
    struct LinkNode* next;
    int data;
}LinkList;
/*说明:都带头结点的单链表*/
/*创建链表*/
void createLinkList(LinkList* head, int* a, int n)
{
    int i = 0;
    LinkNode* node = NULL;
    while (i < n)
    {
        node = new LinkNode;
        node->next =  head->next;
        node->data = a[i];
        head->next = node;
        i++;
    }
}
/*判断链表是否为环,如果为环返回环的结点*/
bool isCircleList(LinkList* head, LinkNode* &headNode)
{
   LinkNode* fast = head;
   LinkNode* slow = head;
   
   while (fast != NULL)
   {
        if (fast->next != NULL)
        {
            fast = fast->next; /*快指针走两步*/
        }
        fast = fast->next;
        slow = slow->next; /*慢指针走一步*/
        if (fast == slow)  /*相遇则跳出*/
        {
            break;
        }
   }
   
   /*走到终点,返回FALSE*/
   if (fast == NULL)
   {
        return false;
   }
   
   /*可以证明:头指针 到 环入口的距离 = 碰撞点p 到 环入口的距离   +  循环多次环*/
   /*参考:http://blog.csdn.net/xiaodeyu2010xiao/article/details/42460203*/
   /*让fast从起点开始走,让slow继续往下走,相遇点就是环的入口*/
   fast = head;
   while (fast != slow)
   {
       fast = fast->next;
       slow = slow->next;
   }
   headNode = slow;
   return true;
   
}

/*k表示从第K个成环*/
bool createCircleList(LinkList* head, int k)
{
     LinkNode* node;
     LinkNode* lastNode = head;
     
     while (lastNode->next != NULL)
     {
        lastNode = lastNode->next;
        k--;
        if (k == 0)
        {
            node = lastNode;
        }
     }
     
     if (k > 0)
     {
        return false;
     }
     lastNode->next = node;/*成环*/
     return true;
}

/*打印链表*/
void printLinkList(LinkList* head)
{
    LinkNode* node = head->next;
    while (node != NULL)
    {
        printf("%d\t", node->data);
        node = node->next;
    }
    printf("\n");
}
int main()
{
    LinkList head = {0};
    LinkNode* node = NULL;
    int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
    createLinkList(&head, a, 9);
    printLinkList(&head);
    createCircleList(&head, 3);
    isCircleList(&head, node);
    if (node != NULL)
    {
        printf("circle node is: %d\n", node->data);
    }
    return 0;
}

判断链表是否成环,如果成环返回成环的第一个结点

标签:

原文地址:http://blog.csdn.net/yuanwei1314/article/details/43082951

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!