-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathswap-kth-beg-end.cpp
130 lines (114 loc) · 2.56 KB
/
swap-kth-beg-end.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
// http://www.geeksforgeeks.org/swap-kth-node-from-beginning-with-kth-node-from-end-in-a-linked-list/
#include <iostream>
using namespace std;
class node {
public:
int data;
node *next;
node(int data) {
this->data = data;
this->next = NULL;
}
};
void swapKth(node* head, int k);
int countList(node *head);
node* addnode(node *head, int data);
void printList(node *head);
void swapKth(node* head, int k) {
if (head == NULL || head->next == NULL)
return;
int n = countList(head);
// k is not appropriate
if (k > n || k < 0) {
cout<<endl<<"k is invalid..";
return;
}
// kth node from first = kth node from last
if (k == n-k+1) {
cout<<endl<<"kth node from first = kth node from last..";
return;
}
// if k = 1, make k = n
if (k == 1)
k = n;
// move x, p_x and y, p_y, n_y to correct positions
node *x = head, *p_x;
for (int i = 0; i < k-1; i++) {
p_x = x;
x = x->next;
}
node *y = head, *p_y, *n_y = NULL;
for (int i = 0; i < n-k; i++) {
p_y = y;
y = y->next;
}
if (y->next != NULL)
n_y = y->next;
// begin changing pointers
// if x is next to y
if (x == y->next) {
node *temp = x;
x = y;
y = temp;
temp = p_x;
p_x = p_y;
p_y = temp;
n_y = y->next;
}
p_x->next = y;
if (y == x->next) {
y->next = x;
}
else {
y->next = x->next;
p_y->next = x;
}
if (n_y != NULL)
x->next = n_y;
}
int countList(node *head) {
if (head == NULL)
return 0;
int count = 0;
node *ptr = head;
while (ptr != NULL) {
count++;
ptr = ptr->next;
}
return count;
}
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, 1);
head = addnode(head, 2);
head = addnode(head, 3);
head = addnode(head, 4);
head = addnode(head, 5);
head = addnode(head, 6);
head = addnode(head, 7);
head = addnode(head, 8);
cout<<"list: ";
printList(head);
cout<<endl<<"kth swap: ";
swapKth(head, 2);
printList(head);
cout<<endl<<endl;
return 0;
}