码迷,mamicode.com
首页 > 其他好文 > 详细

无结点单链表反转

时间:2019-03-06 10:33:48      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:clu   col   int   cout   nbsp   span   style   using   space   

两种方法:新建链表头插法就地反转法

 1 #include<iostream>
 2 using namespace std;
 3 
 4 
 5 struct ListNode {
 6     int val;
 7     ListNode *next;
 8     ListNode(int x) : val(x), next(NULL) {}
 9 };
10 
11 //新建链表头插法
12 ListNode* reverseList(ListNode* head) {
13     if (head == NULL)
14         return head;
15     ListNode* p=NULL;
16     ListNode* pCur = head;
17     while (pCur != NULL)
18     {
19         ListNode* newNode = new ListNode(pCur->val);
20         newNode->next = p;
21         p = newNode;
22         pCur = pCur->next;
23     }
24     return p;
25 }
26 
27 //就地反转法
28 ListNode* reverseList1(ListNode* head)
29 {
30     if (head == NULL || head->next == NULL)
31         return head;
32     ListNode* pre = head;
33     ListNode* pCur = head->next;
34     while (pCur!=NULL)
35     {
36         pre->next = pCur->next;
37         pCur->next = head;
38         head = pCur;
39         pCur = pre->next;
40     }
41     return head;
42 }
43 
44 int main()
45 {
46     ListNode* head=new ListNode(0);
47     ListNode* node1 = new ListNode(1);
48     ListNode* node2 = new ListNode(2);
49     ListNode* node3 = new ListNode(3);
50     ListNode* node4 = new ListNode(4);
51     ListNode* node5 = new ListNode(5);
52     head->next = node1;
53     node1->next = node2;
54     node2->next = node3;
55     node3->next = node4;
56     node4->next = node5;
57     node5->next = NULL;
58 
59     ListNode* pCurrent = head;
60     while (pCurrent != NULL)
61     {
62         cout << pCurrent->val << " ";
63         pCurrent = pCurrent->next;
64     }
65     cout << endl << endl;
66 
67     ListNode* node= reverseList1(head);
68 
69     ListNode* pCurrent1 = node;
70     while (pCurrent1 != NULL)
71     {
72         cout << pCurrent1->val << " ";
73         pCurrent1 = pCurrent1->next;
74     }
75     cout << endl << endl;
76 
77     return 0;
78 }

 

无结点单链表反转

标签:clu   col   int   cout   nbsp   span   style   using   space   

原文地址:https://www.cnblogs.com/hl249853856/p/10481615.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!