-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2.java
More file actions
109 lines (88 loc) · 2.16 KB
/
Q2.java
File metadata and controls
109 lines (88 loc) · 2.16 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import java.util.*;
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
class LinkedList
{
Node head;
public LinkedList()
{
this.head = null;
}
public void insertAtBeginning(int data)
{
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void reverseIterative()
{
System.out.println("Reversing Linklist Iteratively");
Node current = head;
Node prev = null;
Node next = null;
while (current != null)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
public void reverseRecursive()
{
head = reverseUtil(head, null);
}
private Node reverseUtil(Node current, Node prev)
{
if (current == null)
{
return prev;
}
Node next = current.next;
current.next = prev;
return reverseUtil(next, current);
}
public void display()
{
Node current = head;
if (current == null)
{
System.out.println("Linked list is empty.");
return;
}
System.out.print("Linked list = {");
while (current != null)
{
System.out.print(current.data);
if(current.next!=null)
{
System.out.print(" , ");
}
current = current.next;
}
System.out.print("}");
System.out.println();
}
}
public class Q2 {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.insertAtBeginning(3);
linkedList.insertAtBeginning(2);
linkedList.insertAtBeginning(1);
linkedList.display();
linkedList.reverseIterative();
linkedList.display();
linkedList.reverseRecursive();
linkedList.display();
}
}