单链表反转

来源:互联网 发布:网络压力测试工具 编辑:程序博客网 时间:2024/05/01 16:35
#include <stdio.h>#include <malloc.h>struct list{  int data;  struct list *next;       };list *reserve1(list *head){   list *p1,*p2,*p3;       if(head==NULL || head->next==NULL)  {    return head;                }     p1 = head;  p2 = head->next;    while(p2!=NULL)  {     p3 = p2->next;          p2->next = p1;          p1 =p2;          p2 =p3;                    }    head ->next= NULL;    head = p1;  return head;}list *reserve2(list *head,list *pre){     list *p=head->next;     head->next=pre;    // printf("*\n");     if(p==NULL)     {         return head;               }     else     {        return reserve2(p,head);      }}int main(){        list *a[5];        for(int i=0;i<5;i++)    {      a[i] = new list;      a[i]->data = i;      a[i]->next=NULL;                    }         a[0]->next = a[1];    a[1]->next = a[2];    a[2]->next = a[3];    a[3]->next = a[4];    list *root;    root = a[0];        while(root!=NULL)    {       printf("%d->",root->data);       root = root->next;               }        printf("\n");    root = a[0];        root=reserve2(root,NULL);    while(root!=NULL)    {       printf("%d->",root->data);       root = root->next;               }        /*    root = a[0];    root=reserve1(root);        while(root!=NULL)    {       printf("%d->",root->data);       root = root->next;               }    */   //for(;;);return 0;}


原创粉丝点击