已知链表的头节点head,写一个函数把链表逆序
- #include<iostream>
- 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->data<<"/t";
- temp = temp->next;
- }
- cout<<endl;
- delete head1,head2,head3,head4,head5,head6,head7;
- return 0;
- }