-
Notifications
You must be signed in to change notification settings - Fork 590
/
Copy pathkReverse.java
100 lines (82 loc) · 2.42 KB
/
kReverse.java
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
/*
Following is the Node class already written for the Linked List
class LinkedListNode<T> {
T data;
LinkedListNode<T> next;
public LinkedListNode(T data) {
this.data = data;
}
}
*/
public class Solution {
public static LinkedListNode<Integer> reverseLinkedListRec(LinkedListNode<Integer> head) {
//Your code goes here
if (head==null || head.next==null)
{
return head;
}
LinkedListNode<Integer> smallerHead=reverseLinkedListRec(head.next);
LinkedListNode<Integer> node=smallerHead;
while (node.next!=null)
{
node=node.next;
}
node.next=head;
head.next=null;
return smallerHead;
}
public static LinkedListNode<Integer> findTail(LinkedListNode<Integer> head, int k)
{
for (int i=0;i<k && head.next!=null;i++)
{
head=head.next;
}
return head;
}
public static int findLength(LinkedListNode<Integer> head)
{
int count=0;
while(head.next!=null)
{
head=head.next;
count=count+1;
}
return count;
}
public static LinkedListNode<Integer> kReverse(LinkedListNode<Integer> head, int k) {
//Your code goes here
if (head==null || k==0 || k==1)
{
return head;
}
else if (k>findLength(head))
{
return reverseLinkedListRec(head);
}
LinkedListNode<Integer> node=head,nextNode=null,tail=null,prevTail=null,newHead=null;
while(node!=null)
{
tail=findTail(node,k-1);
nextNode=tail.next;
tail.next=null;
newHead=reverseLinkedListRec(node);
//Runner.print(newHead);
if (node==head)
{
tail=head;
tail.next=nextNode;
head=newHead;
}
else
{
tail=node;
tail.next=nextNode;
prevTail.next=newHead;
}
node=nextNode;
prevTail=tail;
//Runner.print(head);
}
return head;
}
}