-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode_offer24.cpp
108 lines (93 loc) · 2.16 KB
/
LeetCode_offer24.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*************************************************************************
> File Name: LeetCode_offer24.cpp
> Author:
> Mail:
> Created Time: Sun 23 Feb 2020 06:53:50 PM PST
************************************************************************/
//反转链表
#include<iostream>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
ListNode(int val) : m_nValue(val), m_pNext(nullptr) {}
};
void ConnectNodes(ListNode* pNode, ListNode* pNext)
{
if (pNode != nullptr)
pNode->m_pNext = pNext;
}
void DestroyList(ListNode* pHead)
{
if (pHead != nullptr)
{
DestroyList(pHead->m_pNext);
delete pHead;
}
}
void PrintList(ListNode* pHead)
{
if (pHead != nullptr)
{
printf("%d ", pHead->m_nValue);
PrintList(pHead->m_pNext);
}
}
ListNode* ReverseList(ListNode* head)
{
if (head == nullptr)
return nullptr;
ListNode* pOrigNode = head;
ListNode* ReverseNode = nullptr;
while (pOrigNode != nullptr)
{
ListNode* pOpeNode = pOrigNode;
pOrigNode = pOrigNode->m_pNext;
pOpeNode->m_pNext = ReverseNode;
ReverseNode = pOpeNode;
}
return ReverseNode;
}
void test(const char* testName, ListNode* pHead)
{
if (testName == nullptr)
return;
printf("%s:\n", testName);
printf("Origin:");
PrintList(pHead);
ListNode*reverseHead = ReverseList(pHead);
printf("Reverse:");
PrintList(reverseHead);
printf("\n");
DestroyList(pHead);
}
ListNode* reverseList2(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode* revHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return revHead;
}
void test1()
{
ListNode* pNode1 = new ListNode(1);
ListNode* pNode2 = new ListNode(2);
ListNode* pNode3 = new ListNode(3);
ListNode* pNode4 = new ListNode(4);
ConnectNodes(pNode1, pNode2);
ConnectNodes(pNode2, pNode3);
ConnectNodes(pNode3, pNode4);
test("Test1", pNode1);
}
void test2()
{
ListNode* pNode1 = new ListNode(1);
test("Test2", pNode1);
}
int main()
{
test1();
test2();
}