-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathList.java
77 lines (63 loc) · 1.76 KB
/
List.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
import java.util.*;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class List {
static Node head;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List obj = new List();
do {
System.out.println("Enter the value:");
int val = sc.nextInt();
sc.nextLine();
obj.append(val);
System.out.println("Do you want to add another node? Type Yes/No");
} while (sc.nextLine().equalsIgnoreCase("yes"));
System.out.print("The elements in the linked list are: ");
obj.display();
obj.Reverse();
System.out.println();
System.out.print("The elements in the reversed linked list are : ");
obj.display();
}
public void append(int data) {
Node newNode = new Node(data);
Node current = head;
if (head == null) {
head = newNode;
return;
} else {
while (current.next != null) {
current = current.next;
}
current.next = newNode;
return;
}
}
public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
public Node Reverse() {
Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
}