链表逆序

链表逆序
链表逆序

//C++ 逆置单链表的两种方法:循环和递归

#include<.h>

struct node

{

int id;

node *next;

}*head;

void add(node *p)

{

node *p1,*p2;

p1=head;

p2=p1;

while(p2)

{

p1=p2;

p2=p2->next;

}

p1->next=p;

p->next=p2;

}

void show(node *p)

{

while(p)

cout<id<next; }

//一种逆置单链表的方法

node* rev(node *head)

{

node *prev=NULL,*next=NULL;

while(head)

{

next=head->next;

head->next=prev;

prev=head;

head=next;

}

return prev;

}

//另一种逆置单链表的方法

/*

node * rev(node *head)//递归方式进行链表逆置{

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

node *tail=rev(head->next);

head->next->next=head;

head->next=NULL;

return tail;

}

*/

void()

{

head=new node;

head->next=NULL;

node *p;

p=new node;

p->id=7;

add(p);

p=new node;

p->id=8;

add(p);

p=new node;

p->id=9;

add(p);

cout<<"输出:"<

show(head->next);

cout<<"逆置后输出:"<

show(rev(head->next));

}

相关主题
相关文档
最新文档