分类: C/C++
2011-11-26 18:06:45
链表逆序,即将原先的链表 a->b->c->d, 变为 d->c->b->a。需要使用三个指针来进行操作。
C++代码:
#include
using namespace std;
class Node
{
public:
int data;
Node* next;
};
Node* ReverseList(Node *head)
{
if((head->next == NULL) || (head == NULL))
return head;
Node *temp1 = head;
Node *temp2;
Node *temp3 = temp1->next;
temp1->next = NULL;
while(temp3->next != NULL)
{
temp2 = temp3;
temp3 = temp3->next;
temp2->next = temp1;
temp1 = temp2;
}
temp3->next = temp1;
return temp3;
}
int main()
{
Node* head1 = new Node();
Node* head2 = new Node();
Node* head3 = new Node();
Node* head4 = new Node();
Node* head5 = new Node();
Node* head6 = new Node();
Node* head7 = new Node();
head1->data=1;
head2->data=2;
head3->data=3;
head4->data=4;
head5->data=5;
head6->data=6;
head7->data=7;
head1->next=head2;
head2->next=head3;
head3->next=head4;
head4->next=head5;
head5->next=head6;
head6->next=head7;
head7->next=NULL;
Node *temp = ReverseList(head1);
while(temp != NULL)
{
cout<
temp = temp->next;
}
cout<
delete head1,head2,head3,head4,head5,head6,head7;
return 0;
}