判断链表是否有环

1641阅读 0评论2012-03-16 
分类:LINUX


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. #define LEN 10

  5. typedef struct node {
  6.     int data;
  7.     struct node *pnext;
  8. } node_t, *pnode_t;

  9. pnode_t create_list(int len)
  10. {
  11.     pnode_t phead, pnew, ptail;
  12.     int i;

  13.     for (i = 0; i < len; i++) {
  14.         pnew = (pnode_t)malloc(sizeof(node_t));
  15.         if (pnew == NULL) {
  16.             printf("malloc fail.\n");
  17.             exit(-1);
  18.         }
  19.         memset(pnew, 0, sizeof(node_t));

  20.         pnew->data = i + 1;
  21.         if (i == 0)
  22.             phead = ptail = pnew;
  23.         else {
  24.             pnew->pnext = NULL;
  25.             ptail->pnext = pnew;
  26.             ptail = pnew;
  27.         }

  28.     }

  29.     /*ptail->pnext = phead;*/
  30.     return phead;
  31. }

  32. int main(int argc, char *argv[])
  33. {
  34.     pnode_t phead, p, q;

  35.     phead = create_list(LEN);

  36.     p = q = phead;
  37.     while (1) {
  38.         p = p->pnext;
  39.         q = q->pnext->pnext;
  40.         if (p == NULL || q == NULL) {
  41.             printf("No Ring!\n");
  42.             return;
  43.         }
  44.         if (p == q) {
  45.             printf("Ring occurred!\n");
  46.             return;
  47.         }
  48.     }
  49.     
  50.     return 0;
  51. }

上一篇:深入理解C程序内存布局
下一篇:ulimit