-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathswapkthlastnode.java
More file actions
69 lines (59 loc) · 1.41 KB
/
swapkthlastnode.java
File metadata and controls
69 lines (59 loc) · 1.41 KB
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
/*
// Information about the class Node
class Node
{
int data;
Node next;
Node(int data)
{
this.data = data;
next = null;
}
}
*/
static Node swapkthnode(Node head, int num, int k)
{
if(k>num) {
return head;
}
Node KthstartNode =head;
Node KthstartNode_prev = null;
Node kthlastNode= head ;
Node kthlastNode_prev = null;
int count = 1;
while(count<k) {
KthstartNode_prev = KthstartNode;
KthstartNode = KthstartNode.next;
count++;
}
// kthstartNode will point out to the kth node from starting
// KthstartNode_prev will point to the kth previous node from starting
int count1 = num-k;
while(count1>0) {
kthlastNode_prev =kthlastNode;
kthlastNode = kthlastNode.next;
count1--;
}
// kthlastNode will point out to the kth node from ending
// kthlastNode_prev will point to the kth previous node from ending
if(KthstartNode_prev!=null) {
KthstartNode_prev.next =kthlastNode;
}
if(kthlastNode_prev!=null) {
kthlastNode_prev.next = KthstartNode;
}
Node temp = KthstartNode.next;
KthstartNode.next = kthlastNode.next;
kthlastNode.next = temp;
if(k==1) {
head = kthlastNode;
}
if(k==num)
{
head = KthstartNode;
}
return head;
}
// Find kth node in given linked list from starting
// Find the kth node in given linked list from the ending
// Find the middle noe of linked list