[AlgoExpert] Zip Linked List

Zip 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
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
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* split(LinkedList *head) {
LinkedList *slow = head, *fast = head, *end = head;
while(fast and fast->next) {
end = slow;
slow = slow->next;
fast = fast->next->next;
}
if(fast) {
end = slow;
slow = slow->next;
}
end->next = nullptr;
return slow;
}

LinkedList* reverse(LinkedList* head) {
LinkedList *dummy = new LinkedList(-1);
dummy->next = head;
while(head and head->next) {
LinkedList* tmp = head->next;
head->next = tmp->next;

tmp->next = dummy->next;
dummy->next = tmp;
}
return dummy->next;
}

void connect(LinkedList* head1, LinkedList* head2) {
LinkedList *nxt1 = head1, *nxt2 = head2;
while(nxt1 and nxt2) {
nxt1 = head1->next;
nxt2 = head2->next;

head1->next = head2;
head2->next = nxt1;

head1 = nxt1;
head2 = nxt2;
}
}

LinkedList *zipLinkedList(LinkedList *linkedList) {
LinkedList* res = linkedList;
LinkedList* second = split(linkedList);
LinkedList* reversed = reverse(second);
connect(linkedList, reversed);

return res;
}

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