-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked List 2:kReverse
47 lines (39 loc) · 1.11 KB
/
Linked List 2:kReverse
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
public class Solution {
public static LinkedListNode<Integer> kReverse(LinkedListNode<Integer> head, int k) {
if(head==null)
return head;
if(head.next==null)
return head;
if(k==0)
return head;
LinkedListNode<Integer> h1=head,h2,t1=head;
int count=1;
while(count<k && t1.next!=null)
{
t1=t1.next;
count++;
}
h2=t1.next;
t1.next=null;
DoubleNode ans=reversePart(h1);
LinkedListNode<Integer> secondHead=kReverse(h2,k);
ans.tail.next=secondHead;
return ans.head;
}
private static DoubleNode reversePart(LinkedListNode<Integer> head)
{
if(head==null || head.next==null)
{ DoubleNode ans=new DoubleNode();
ans.head=head;
ans.tail=head;
return ans;}
DoubleNode ans=reversePart(head.next);
ans.tail.next=head;
head.next=null;
ans.tail=ans.tail.next;
return ans;
}
}
class DoubleNode{
LinkedListNode<Integer> head;
LinkedListNode<Integer> tail;}