-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlist-alternate-split.cpp
76 lines (67 loc) · 1.6 KB
/
list-alternate-split.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
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
// http://www.geeksforgeeks.org/alternating-split-of-a-given-singly-linked-list/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
void alternateSplit(Node *head);
Node* addNode(Node *head, int data);
void printList(Node *head);
void alternateSplit(Node *head) {
if (head == NULL || head->next == NULL)
return;
Node* list2 = NULL;
Node *prev = head, *curr = head->next;
while (curr != NULL && curr->next != NULL) {
prev->next = curr->next;
prev = prev->next;
list2 = addNode(list2, curr->data);
curr = curr->next->next;
}
if (curr != NULL)
list2 = addNode(list2, curr->data);
if (prev->next != NULL)
prev->next = NULL;
cout<<endl;
printList(head);
cout<<endl;
printList(list2);
}
Node* addNode(Node *head, int data) {
if (head == NULL)
return new Node(data);
Node *ptr = head;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = new Node(data);
return head;
}
void printList(Node *head) {
if (head == NULL)
return;
while (head != NULL) {
cout<<head->data<<" ";
head = head->next;
}
}
int main() {
Node *head = NULL;
head = addNode(head, 0);
head = addNode(head, 1);
head = addNode(head, 0);
head = addNode(head, 1);
head = addNode(head, 0);
head = addNode(head, 1);
cout<<"list: ";
printList(head);
cout<<endl<<"alternate split..";
alternateSplit(head);
cout<<endl;
return 0;
}