- #include<stdio.h>
- typedef struct link
- {
- int data;
- struct link *next;
- }node;
- int isCircle(node *head)
- {
- node *p=head,*q=head;
- while(p->next && q->next)
- {
- p=p->next;
- if(NULL==(q=q->next->next))
- return 0;
- if(p==q)
- return 1;
- }
- return 0;
- }
- node *create()
- {
- node *head,*p,*s;
- int x,cycle=1;
- head=(node *)malloc(sizeof(node));
- p=head;
- printf("please input the data (end with zero):\n");
- while(cycle)
- {
- scanf("%d",&x);
- if(x!=0)
- {
- s=(node *)malloc(sizeof(node));
- s->data=x;
- p->next=s;
- p=s;
- }
- else
- cycle=0;
- }
- head=head->next; /* 删除头结点 */
- p->next=NULL;
- printf("\nhead = %d\n",head->data);
- return (head);
- }
- void display(node *head)
- {
- node *p;
- int n=0;
- p=head;
- while(p!=NULL)
- {
- p=p->next;
- n++;
- }
- printf("\nNow,These %d recodes are :\n",n);
- p=head;
- if(head!=NULL)
- while(p)
- {
- printf(" %d -> ",p->data);
- p=p->next;
- }
- printf("\n");
- }
- node *reverse(node *head)
- {
- /* p1 -> p2 -> p3 先让p2逆置:
- p1 <- p2 -> p3 然后p1,p2向后推进:
- xx <- p1 -> p2 -> p3 重复进行直到p2为空。
- */
- node *p1,*p2,*p3;
- if(head == NULL || head->next == NULL)
- return head;
- /* p1=head, p2=p1->next; This is OK. */
- p1=head;
- p2=p1->next;
- p1->next=NULL;
- while(p2)
- {
- p3=p2->next;
- p2->next=p1;
- p1=p2;
- p2=p3;
- }
- head->next = NULL;
- head = p1;
- return head;
- }
- main()
- {
- node *head;
- head = create();
- /* display(head); */
- head = reverse(head);
- display(head);
- }
从尾到头遍历单链表:
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) |