forked from harsh9539/linkedlist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist.java
More file actions
128 lines (108 loc) · 2.72 KB
/
linkedlist.java
File metadata and controls
128 lines (108 loc) · 2.72 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
class LinkedList<T> {
Node<T> head;
static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
this.next = null;
}
}
public void addFirst(T data) {
Node<T> temp = new Node<T>(data);
if (head == null) {
head = temp;
return;
}
temp.next = head;
head = temp;
}
public void addLast(T data) {
Node<T> temp = new Node<T>(data);
if (head == null) {
head = temp;
return;
}
Node<T> curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = temp;
}
public void printList() {
if(head == null){
System.out.println("List is empty");
return;
}
Node<T> curr = head;
while (curr != null) {
System.out.print(curr.data + "->");
curr = curr.next;
}
System.out.println("null");
}
public void removeFirst() {
if (head == null) {
System.out.println("List is empty. Cannot remove.");
return;
}
head = head.next;
}
public void removeLast() {
if (head == null) {
System.out.println("List is empty. Cannot remove.");
return;
}
if (head.next == null) {
// When the head is the only element
head = null;
return;
}
Node<T> curr = head;
Node<T> prev = null;
while (curr.next != null) {
prev = curr;
curr = curr.next;
}
prev.next = null;
}
static Node removeLastNode(Node head)
{
if (head == null)
return null;
if (head.next == null) { return null;
}
Node second_last = head;
while (second_last.next.next != null)
second_last = second_last.next;
second_last.next = null;
return head;
}
Node reverse(Node node)
{
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
// ll.addLast(10);
// ll.addLast(20);
// ll.addLast(30);
// ll.addLast(40);
// ll.addFirst(50);
ll.addLast("Hello");
ll.addLast("i");
ll.addLast("am");
ll.addLast("Harsh Goyal");
ll.printList();
}
}