Chinaunix首页 | 论坛 | 博客
  • 博客访问: 243862
  • 博文数量: 62
  • 博客积分: 973
  • 博客等级: 准尉
  • 技术积分: 530
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-16 23:25
文章分类

全部博文(62)

文章存档

2013年(1)

2012年(14)

2011年(47)

分类: C/C++

2011-12-21 18:58:36

  1. #include<stdio.h>

  2. typedef struct link
  3. {
  4.     int data;
  5.     struct link *next;
  6. }node;

  7. int isCircle(node *head)
  8. {
  9.     node *p=head,*q=head;
  10.     while(p->next && q->next)
  11.     {
  12.         p=p->next;
  13.         if(NULL==(q=q->next->next))
  14.             return 0;
  15.         if(p==q)
  16.           return 1;
  17.     }
  18.     return 0;
  19. }

  20. node *create()
  21. {
  22.     node *head,*p,*s;
  23.     int x,cycle=1;
  24.     head=(node *)malloc(sizeof(node));
  25.     p=head;
  26.     printf("please input the data (end with zero):\n");
  27.     while(cycle)
  28.     {
  29.         scanf("%d",&x);
  30.         if(x!=0)
  31.         {
  32.             s=(node *)malloc(sizeof(node));
  33.             s->data=x;
  34.             p->next=s;
  35.             p=s;
  36.         }
  37.         else
  38.           cycle=0;
  39.     }
  40.     head=head->next; /* 删除头结点 */
  41.     p->next=NULL;
  42.     printf("\nhead = %d\n",head->data);
  43.     return (head);
  44. }

  45. void display(node *head)
  46. {
  47.     node *p;
  48.     int n=0;
  49.     p=head;
  50.     while(p!=NULL)
  51.     {
  52.         p=p->next;
  53.         n++;
  54.     }
  55.     printf("\nNow,These %d recodes are :\n",n);
  56.     p=head;
  57.     if(head!=NULL)
  58.       while(p)
  59.       {
  60.           printf(" %d -> ",p->data);
  61.           p=p->next;
  62.       }
  63.     printf("\n");
  64. }

  65. node *reverse(node *head)
  66. {
  67.     /* p1 -> p2 -> p3 先让p2逆置:
  68.        p1 <- p2 -> p3 然后p1,p2向后推进:
  69.        xx <- p1 -> p2 -> p3 重复进行直到p2为空。
  70.     */
  71.     node *p1,*p2,*p3;

  72.     if(head == NULL || head->next == NULL)
  73.         return head;

  74.     /* p1=head, p2=p1->next; This is OK. */
  75.     p1=head;
  76.     p2=p1->next;
  77.     p1->next=NULL;
  78.     while(p2)
  79.     {
  80.         p3=p2->next;
  81.         p2->next=p1;
  82.         p1=p2;
  83.         p2=p3;
  84.     }

  85.     head->next = NULL;
  86.     head = p1;
  87.     return head;
  88. }

  89. main()
  90. {
  91.     node *head;
  92.     head = create();
  93.     /* display(head); */
  94.     head = reverse(head);
  95.     display(head);

  96. }

从尾到头遍历单链表:

void rvs_visit(node* head)
{
    if(head != NULL)
    {
        if(head->next != NULL)    //visit the next node first
        {
            rvs_visit(head->next);
        }
        printf("%d <-", head->data);
    }
}

阅读(1879) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~