您的位置:首页 > 其它

链表逆序

2010-07-14 10:30 148 查看
已知链表的头节点head,写一个函数把链表逆序



1.#include<iostream> 2.using namespace std;
3.4.class Node
5.{
6.public:
7. int data;
8. Node* next;
9.};
10.11.Node* ReverseList(Node *head)
12.{
13. if((head->next == NULL) || (head == NULL))
14. return head;
15.16. Node *temp1 = head;
17. Node *temp2;
18. Node *temp3 = temp1->next;
19. temp1->next = NULL;
20. while(temp3->next != NULL)
21. {
22. temp2 = temp3;
23. temp3 = temp3->next;
24. temp2->next = temp1;
25. temp1 = temp2;
26. }
27. temp3->next = temp1;
28. return temp3;
29.}
30.31.int main()
32.{
33. Node* head1 = new Node();
34. Node* head2 = new Node();
35. Node* head3 = new Node();
36. Node* head4 = new Node();
37. Node* head5 = new Node();
38. Node* head6 = new Node();
39. Node* head7 = new Node();
40.41. head1->data=1;
42. head2->data=2;
43. head3->data=3;
44. head4->data=4;
45. head5->data=5;
46. head6->data=6;
47. head7->data=7;
48.49. head1->next=head2;
50. head2->next=head3;
51. head3->next=head4;
52. head4->next=head5;
53. head5->next=head6;
54. head6->next=head7;
55. head7->next=NULL;
56.57. Node *temp = ReverseList(head1);
58.59. while(temp != NULL)
60. {
61. cout<<temp->data<<"/t";
62. temp = temp->next;
63. }
64. cout<<endl;
65.
66. delete head1,head2,head3,head4,head5,head6,head7;
67. return 0;
68.}
文章出处:飞诺网(www.firnow.com):http://dev.firnow.com/course/3_program/c++/cppjs/2008930/146890.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: