自己寫了單鏈表的逆轉程序,記錄如下,歡迎指正
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
Node * reverse(Node *head)
{
if(head->next==NULL)
return head;
Node *t1=head->next;
if(t1==NULL)
return head;
Node *t2=t1->next;
t1->next=NULL;
while(t2->next!=NULL)
{
Node *t3=t2->next;
t2->next=t1;
t1=t2;
t2=t3;
}
t2->next=t1;
head->next=t2;
return head;
}
void main()
{
Node *list=new Node[5];
Node *head=new Node;
head->next=&list[0];
list[0].data=1;
list[0].next=&list[1];
list[1].data=2;
list[1].next=&list[2];
list[2].data=3;
list[2].next=&list[3];
list[3].data=4;
list[3].next=&list[4];
list[4].data=5;
list[4].next=NULL;
Node *p;
p=head;
while(p->next!=NULL)
{
printf("%d\n",p->next->data);
p=p->next;
}
reverse(head);
printf("逆轉後\n");
p=head;
while(p->next!=NULL)
{
printf("%d\n",p->next->data);
p=p->next;
}
delete head;
delete []list;
}
運行結果:
作者“菜鳥變身記”