Skip to content

Commit e1664ad

Browse files
Create rishi.java
1 parent d2c2623 commit e1664ad

File tree

1 file changed

+149
-0
lines changed

1 file changed

+149
-0
lines changed

rishi.java

+149
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
public class LinkedList {
2+
public static class Node{
3+
int data;
4+
Node next;
5+
6+
public Node(int data){
7+
this.data = data;
8+
this.next = null;
9+
}
10+
}
11+
12+
public static Node head;
13+
public static Node tail;
14+
public static int size;
15+
16+
public void addFirst(int data){
17+
Node newNode = new Node(data);
18+
size++;
19+
if(head == null){
20+
head = tail = newNode;
21+
return;
22+
}
23+
24+
newNode.next = head;
25+
head = newNode;
26+
}
27+
28+
public void addLast(int data){
29+
Node newNode = new Node(data);
30+
size++;
31+
if(head == null){
32+
head = tail = newNode;
33+
return;
34+
}
35+
36+
tail.next = newNode;
37+
38+
tail = newNode;
39+
}
40+
41+
public void addMidd(int idx, int data) {
42+
if(idx == 0){
43+
addFirst(data);
44+
return;
45+
}
46+
Node newNode = new Node(data);
47+
size++;
48+
Node temp = head;
49+
int i = 0;
50+
while (i < idx) {
51+
temp = temp.next;
52+
i++;
53+
}
54+
55+
newNode.next = temp.next;
56+
temp.next = newNode;
57+
}
58+
59+
public int removeFirst() {
60+
if(head == null){
61+
System.out.println("LL is empty");
62+
return Integer.MIN_VALUE;
63+
}
64+
65+
int val = head.data;
66+
size--;
67+
if(head == tail){
68+
head = tail = null;
69+
return val;
70+
}
71+
head = head.next;
72+
return val;
73+
}
74+
75+
public int removeLast() {
76+
if(head == null){
77+
System.out.println("LL is empty");
78+
return Integer.MIN_VALUE;
79+
}
80+
81+
int val = head.data;
82+
size--;
83+
if(head == tail){
84+
head = tail = null;
85+
86+
return val;
87+
}
88+
Node prev = head;
89+
90+
while(prev.next!=tail){
91+
prev = prev.next;
92+
}
93+
val = prev.next.data;
94+
prev.next = tail;
95+
tail = prev;
96+
97+
return val;
98+
}
99+
100+
public void print() {
101+
Node temp = head;
102+
103+
while (temp!=null) {
104+
System.out.print(temp.data + "->");
105+
temp = temp.next;
106+
}
107+
System.out.print("null");
108+
System.out.println();
109+
}
110+
111+
// Searching In linked list
112+
113+
public int itrSearch(int key) {
114+
if(head == null){
115+
return -1;
116+
}
117+
118+
int i = 0;
119+
Node temp = head;
120+
121+
while(temp!=null){
122+
if(temp.data == key)
123+
return i;
124+
i++;
125+
temp = temp.next;
126+
}
127+
128+
return -1;
129+
}
130+
131+
// Searching Using recursion
132+
133+
// public int recSearch(int key, Node start) {
134+
135+
// }
136+
137+
public static void main(String[] args) {
138+
LinkedList ll = new LinkedList();
139+
140+
ll.addFirst(1);
141+
ll.print();
142+
ll.addLast(2);
143+
ll.print();
144+
ll.addLast(4);
145+
ll.print();
146+
ll.addMidd(2, 3);
147+
ll.print();
148+
}
149+
}

0 commit comments

Comments
 (0)