[AlgoExpert] Node Swap

Node Swap

  • 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
28
29
using namespace std;

// This is an input struct. Do not edit.
class LinkedList {
public:
int value;
LinkedList *next = nullptr;

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

LinkedList *nodeSwap(LinkedList *head) {
if(head == nullptr) return nullptr;
LinkedList *dummy = new LinkedList(-1);
dummy->next = head;
LinkedList *prv = dummy, *now = head, *nxt;
while(now) {
if(now->next == nullptr) break;
nxt = now->next;
LinkedList* tmp = nxt->next;
prv->next = nxt;
nxt->next = now;
now->next = tmp;

prv = now;
now = tmp;
}
return dummy->next;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/node-swap/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.