forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseKNodes.java
83 lines (73 loc) · 1.32 KB
/
ReverseKNodes.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
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/ReverseKNodes.php.html
*/
package com.dsalgo;
public class ReverseKNodes
{
public static void main(String[] args)
{
int[] arr =
{ 4, 5, 3, 6, 8, 3, 5, 7, 3, 7, 9, 4, 6 };
Node head = createLinkedList(arr);
printLinkedList(head);
head = reverse(head, 4);
printLinkedList(head);
}
static Node reverse(Node head, int k)
{
Node current = head;
Node next = null;
Node prev = null;
int count = 0;
while (current != null && count < k)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
if (next != null)
{
head.next = reverse(next, k);
}
return prev;
}
private static void printLinkedList(Node head)
{
while (head != null)
{
System.out.print(head.value + "->");
head = head.next;
}
System.out.println();
}
private static Node createLinkedList(int[] arr)
{
Node head = null;
Node current = null;
for (int element : arr)
{
if (head == null)
{
head = new Node(element);
current = head;
} else
{
current.next = new Node(element);
current = current.next;
}
}
return head;
}
static class Node
{
public Node next;
public int value;
public Node(int value)
{
this.value = value;
}
}
}