[AlgoExpert] Reverse Linked List

Reverse Linked List

  • Time : O(n)
  • Space : O(1)
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
using namespace std;

class LinkedList {
public:
int value;
LinkedList *next;

LinkedList(int value) {
this->value = value;
this->next = nullptr;
}
};

LinkedList *reverseLinkedList(LinkedList *head) {
LinkedList* dummy = new LinkedList(-1);
LinkedList* tmp;

while(head) {
tmp = head->next;
head->next = dummy->next;
dummy->next = head;
head = tmp;
}

return dummy->next;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/reverse-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.