-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.java
119 lines (104 loc) · 2.63 KB
/
LinkedList.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
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
import java.util.*;
class LinkedList{
private Node head;
private Node tail;
private int size;
Node temp = head;
public LinkedList(){ //Default Constructor
this.size = 0;
}
public void insertFirst(int val){
Node node = new Node(val);
node.next = head;
head = node;
if(tail == null){
tail = head;
}
size+=1;
}
public void insertLast(int val){
if(tail == null){
insertFirst(val);
return;
}
Node node = new Node(val);
tail.next = node;
tail = node;
size++;
}
public void insertRecc(int val, int ind){
if(ind!=0){
temp=temp.next;
insertRecc(val,--ind);
}
Node node = new Node(val);
if(head == null)
node=head;
Node after= temp.next;
temp.next = node;
node.next = after;
size++;
}
public void insertMiddle(int val, int ind){
if(ind == 0){
insertFirst(val);
return;
}
if (ind == (size-1)){
insertLast(val);
return;
}
int i=1;
Node temp = head;
while(i!=ind){
temp = temp.next;
i++;
}
Node node = new Node(val, temp.next);
temp.next = node;
size++;
}
public int deleteFirst(){
int val= head.value;
head= head.next;
size--;
return val;
}
public int deleteLast(){
if (size <= 1){
return deleteFirst();
}
Node secLast = get(size-2);
int val = secLast.next.value;
tail = secLast;
tail.next = null;
size --;
return val;
}
public Node get(int ind){
Node node = head;
for(int i=0; i<ind; i++){
node = node.next;
}
return node;
}
public void display(){
Node temp = head;
while(temp!= null){
System.out.print(temp.value + " -> ");
temp= temp.next;
}
System.out.println("Null");
}
private class Node{
private int value;
private Node next;
public Node(int value){ //Constructor
this.value = value;
}
public Node(int value, Node next){ //Dynamic Constructor
this.value =value;
this.next = next;
}
}
}