Skip to content

Commit a93f192

Browse files
authored
Update kReverse
1 parent 5c97701 commit a93f192

File tree

1 file changed

+102
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 8 - Linked Lists II

1 file changed

+102
-0
lines changed

Course 2 - Data Structures in JAVA/Lecture 8 - Linked Lists II/kReverse

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,105 @@ Sample Output 2 :
4242
1 2 3 4 5
4343
40 30 20 10
4444
*/
45+
46+
/*
47+
48+
Following is the Node class already written for the Linked List
49+
50+
class LinkedListNode<T> {
51+
T data;
52+
LinkedListNode<T> next;
53+
54+
public LinkedListNode(T data) {
55+
this.data = data;
56+
}
57+
}
58+
59+
*/
60+
61+
public class Solution {
62+
63+
public static LinkedListNode<Integer> reverseLinkedListRec(LinkedListNode<Integer> head) {
64+
//Your code goes here
65+
66+
if (head==null || head.next==null)
67+
{
68+
return head;
69+
}
70+
LinkedListNode<Integer> smallerHead=reverseLinkedListRec(head.next);
71+
LinkedListNode<Integer> node=smallerHead;
72+
while (node.next!=null)
73+
{
74+
node=node.next;
75+
}
76+
node.next=head;
77+
head.next=null;
78+
return smallerHead;
79+
}
80+
81+
public static LinkedListNode<Integer> findTail(LinkedListNode<Integer> head, int k)
82+
{
83+
for (int i=0;i<k && head.next!=null;i++)
84+
{
85+
head=head.next;
86+
}
87+
return head;
88+
89+
90+
}
91+
92+
public static int findLength(LinkedListNode<Integer> head)
93+
{
94+
int count=0;
95+
while(head.next!=null)
96+
{
97+
head=head.next;
98+
count=count+1;
99+
}
100+
return count;
101+
}
102+
103+
public static LinkedListNode<Integer> kReverse(LinkedListNode<Integer> head, int k) {
104+
//Your code goes here
105+
if (head==null || k==0 || k==1)
106+
{
107+
return head;
108+
}
109+
else if (k>findLength(head))
110+
{
111+
return reverseLinkedListRec(head);
112+
}
113+
114+
LinkedListNode<Integer> node=head,nextNode=null,tail=null,prevTail=null,newHead=null;
115+
while(node!=null)
116+
{
117+
tail=findTail(node,k-1);
118+
nextNode=tail.next;
119+
tail.next=null;
120+
newHead=reverseLinkedListRec(node);
121+
//Runner.print(newHead);
122+
if (node==head)
123+
{
124+
tail=head;
125+
tail.next=nextNode;
126+
head=newHead;
127+
128+
}
129+
else
130+
{
131+
tail=node;
132+
tail.next=nextNode;
133+
prevTail.next=newHead;
134+
135+
}
136+
node=nextNode;
137+
prevTail=tail;
138+
//Runner.print(head);
139+
140+
}
141+
return head;
142+
143+
144+
}
145+
146+
}

0 commit comments

Comments
 (0)