-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path26_CopyComplexList.cpp
134 lines (116 loc) · 2.19 KB
/
26_CopyComplexList.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <iostream>
#include <cstdio>
using namespace std;
#define MAX 1001
struct ComplexListNode
{
int value;
ComplexListNode *next;
ComplexListNode *sibling;
};
void Create(int n, ComplexListNode **head)
{
ComplexListNode* arr[MAX];
int i, tmp;
if (n <= 0)
{
*head = NULL;
return ;
}
for (i = 0; i < n; i++)
{
arr[i] = new ComplexListNode;
arr[i]->next = NULL;
arr[i]->sibling = NULL;
arr[i]->value = 0;
}
for (i = 0; i < n; i++)
{
scanf("%d", &tmp);
arr[i]->value = tmp;
if (i != n - 1)
arr[i]->next = arr[i + 1];
}
for (i = 0; i < n; i++)
{
scanf("%d", &tmp);
if (tmp != 0)
arr[i]->sibling = arr[tmp - 1];
}
*head = arr[0];
}
void CloneNodes(ComplexListNode *head)
{
ComplexListNode *index, *clone_index;
index = head;
while (index)
{
clone_index = new ComplexListNode;
clone_index->value = index->value;
clone_index->next = index->next;
index->next = clone_index;
clone_index->sibling = NULL;
index = clone_index->next;
}
}
void ConnectSiblingNodes(ComplexListNode *head)
{
ComplexListNode *index = head;
while (index)
{
if (index->sibling)
index->next->sibling = index->sibling->next;
index = index->next->next;
}
}
ComplexListNode *ReconnectNodes(ComplexListNode *head)
{
ComplexListNode *clone_head;
ComplexListNode *index = head, *clone_index;
if (head == NULL)
return NULL;
clone_head = index->next;
index->next = clone_head->next;
index = index->next;
clone_index = clone_head;
while (index)
{
clone_index->next = index->next;
clone_index = clone_index->next;
index->next = clone_index->next;
index = index->next;
}
return clone_head;
}
ComplexListNode* Clone(ComplexListNode *head)
{
CloneNodes(head);
ConnectSiblingNodes(head);
return ReconnectNodes(head);
}
void PrintSibling(ComplexListNode *head)
{
ComplexListNode *index = head;
if (index == NULL)
return ;
while (index)
{
if (index->sibling)
printf("%d %d\n", index->value, index->sibling->value);
else
printf("%d 0\n", index->value);
index = index->next;
}
}
int main(void)
{
int n;
while (cin >> n)
{
ComplexListNode *head, *clone_head;
Create(n, &head);
clone_head = Clone(head);
PrintSibling(clone_head);
}
return 0;
}