-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathReverseLL.h
81 lines (75 loc) · 2.08 KB
/
ReverseLL.h
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
//
// ReverseLL.h
// linkedList
//
// Created by junl on 2019/10/31.
// Copyright © 2019 junl. All rights reserved.
//
#ifndef ReverseLL_hpp
#define ReverseLL_hpp
#include <stdio.h>
#include "creatlist.h"
/*
分别实现反转单向链表和反转双向链表
*/
namespace itinterviews {
class ReverseLL{
public:
ListNode *solveSL(ListNode *head){
if (!head || !head->next) {
return head;
}
ListNode *pre,*ct,*next;
pre = head;
ct = pre->next;
pre->next = nullptr;
while (ct) {
next = ct->next;
ct->next = pre;
pre = ct;
ct = next;
}
return pre;
};
DoubleNode* solveDL(DoubleNode *head){
if (!head || !head->next) {
return head;
}
DoubleNode *pre,*ct,*next;
pre = head;
ct = pre->next;
pre->next = nullptr;
while (ct) {
next = ct->next;
ct->next = pre;
pre->pre = ct;
pre = ct;
ct = next;
}
pre->pre = nullptr;
return pre;
}
};
void test_ReverseLL(){
std::cout << "--------test_ReverseLL---------" << std::endl;
ListNode *head = codinginterviews::creatLists({1,2,3,4,5})->next;
head->print();
class ReverseLL so;
so.solveSL(head)->print();
DoubleNode *dhead = codinginterviews::creatDoubleLists({1,2,3,4,5})->next;
dhead->print();
dhead = so.solveDL(dhead);
dhead->print();
DoubleNode *tailNode = dhead;
while (tailNode->next) {
tailNode = tailNode->next;
}
std::cout << "验证双向链表反转过后的pre关系" << std::endl;
while (tailNode) {
std::cout << tailNode->val << ", ";
tailNode = tailNode->pre;
}
std::cout << std::endl;
}
}
#endif /* ReverseLL_hpp */