-
Notifications
You must be signed in to change notification settings - Fork 0
/
FoldLinkList.cpp
81 lines (80 loc) · 1.5 KB
/
FoldLinkList.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
77
78
79
80
81
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node{
int data;
node* next;
};
node* newNode(int data){
node* temp = (node*) malloc(sizeof(node));
temp->data = data;
temp->next = NULL;
return temp;
}
void insert(node** head, int data){
if(*head==NULL){
*head = newNode(data);
return;
}
node* ptr = *head;
while(ptr->next){
ptr= ptr->next;
}
ptr->next = newNode(data);
}
void print(node* head){
while(head){
cout<<head->data<<" ";
head= head->next;
}
}
node* reverse(node* head){
node* cur = head;
node* prev = NULL;
node* next;
while(cur){
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
node* fold(node* head){
node* slow= head;
node* fast = head;
node* prev;
while(fast&&fast->next){
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev ->next=NULL;
node* head2 = reverse(slow);
/*// print(head);
cout<<endl;
print(head2);*/
node* res;
while(head ||head2){
if(head){
insert(&res, head->data);
head = head->next;
}
if(head2){
insert(&res, head2->data);
head2 =head2->next;
}
}
return res;
}
int main() {
node* h = NULL;
insert(&h, 1);
insert(&h, 2);
insert(&h, 3);
insert(&h, 4);
insert(&h, 5);
node* f = fold(h);
print(f);
return 0;
}