-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReversLinkedListInGroups.java
More file actions
61 lines (51 loc) · 969 Bytes
/
Copy pathReversLinkedListInGroups.java
File metadata and controls
61 lines (51 loc) · 969 Bytes
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
public class ReversLinkedListInGroups {
public static void main(String[] args){
//prepare a linked list
RNode n1=new RNode(1);
RNode n2=new RNode(2);
RNode n3=new RNode(3);
RNode n4=new RNode(4);
RNode n5=new RNode(5);
RNode n6=new RNode(6);
RNode n7=new RNode(7);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=n6;
n6.next=n7;
//Call the method to reverse the linked list
RNode r=reverseLinkedList(n1,2);
while(r!=null){
System.out.println(r.data);
r=r.next;
}
}
static RNode reverseLinkedList(RNode head,int k ){
if(head==null){
return null;
}
RNode current=head;
RNode previous=null;
RNode next=null;
int count=0;
while(current!=null && count<k){
next=current.next;
current.next=previous;
previous=current;
current=next;
count++;
}
if(current!=null){
head.next=reverseLinkedList(current, k);
}
return previous;
}
}
class RNode{
int data;
RNode next;
RNode(int data){
this.data=data;
}
}