-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-a-linked-list.cpp
50 lines (40 loc) · 1.15 KB
/
reverse-a-linked-list.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
/*
* Complete the 'reverse' function below.
*
* The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
* The function accepts INTEGER_SINGLY_LINKED_LIST llist as parameter.
*/
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
[[nodiscard]] auto reverse(SinglyLinkedListNode* llist) -> SinglyLinkedListNode* {
//recursively
// if (llist == nullptr || llist->next == nullptr) {
// return llist;
// }
// auto reversed_head = reverse(llist->next);
// llist->next->next = llist; //node AFTER me, point back at me
// llist->next = nullptr; //destroy my connection to next node (already pointing at me)
// return reversed_head;
//iteratively
SinglyLinkedListNode* prev = nullptr;
SinglyLinkedListNode* current = llist;
SinglyLinkedListNode* next = current->next;
if (current == nullptr) {
return llist;
}
while (next != nullptr) {
current->next = prev;
prev = current;
current = next;
next = next->next;
}
current->next = prev;
return current;
}