-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseLLKNodes.java
More file actions
85 lines (84 loc) · 1.68 KB
/
reverseLLKNodes.java
File metadata and controls
85 lines (84 loc) · 1.68 KB
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
import java.util.*;
public class Main
{
static class Node
{
int data;
Node next;
Node(int data)
{
this.data=data;
}
}
Node head;
void insert(int data)
{
Node n=new Node(data);
if(head==null)
{
head=n;
return;
}
Node ptr=head;
while(ptr.next!=null)
{
ptr=ptr.next;
}
ptr.next=n;
return;
}
void reversek(int k)
{
Stack<Node> mystack = new Stack<Node> ();
Node current = head;
Node prev = null;
while (current != null)
{
int count = 0;
while (current != null && count < k)
{
mystack.push(current);
current = current.next;
count++;
}
while (mystack.size() > 0)
{
if (prev == null)
{
prev = mystack.peek();
head = prev;
mystack.pop();
}
else
{
prev.next = mystack.peek();
prev = prev.next;
mystack.pop();
}
}
}
prev.next = null;
print(head);
}
void print(Node h)
{
Node ptr=h;
while(ptr!=null)
{
System.out.print(ptr.data+" ");
ptr=ptr.next;
}
}
public static void main(String[] args) {
Main a= new Main();
Scanner s=new Scanner(System.in);
System.out.println("Enter the size");
int size=s.nextInt();
while(size--!=0)
{
a.insert(s.nextInt());
}
int k=s.nextInt();
a.reversek(k);
}
}