-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplementationLL.java
More file actions
132 lines (121 loc) · 2.79 KB
/
implementationLL.java
File metadata and controls
132 lines (121 loc) · 2.79 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
129
130
131
132
import java.io.EOFException;
import java.util.List;
class SLL{//user defined data structure
Node head;
Node tail;
int si;
void insertAtEnd(int val){
Node temp=new Node(val);
if(head==null){
head=tail=temp;
}
else{
tail.next=temp;
tail=temp;
}
si++;
}
void display(){
Node temp=head;
while(temp!=null){
System.out.println(temp.val);
temp=temp.next;
}
}
void size(){
System.out.println("length of linked list is:"+si);
}
void insertAtHead(int val){
Node temp=new Node(val);
if(head==null){
head=tail=temp;
}
else{
temp.next=head;
head=temp;
}
}
void insert(int idx,int val){
if(idx==0){
insertAtHead(val);
return;
}
if(idx==si){
insertAtEnd(val);
return;
}
if(idx>si){
System.out.println("Invalid index");
return;
}
Node temp=new Node(val);
Node x=head;
for(int i=1;i<=idx-1;i++){
x=x.next;
}
temp.next=x.next;
x.next=temp;
}
int get(int idx){
if(idx<si){
return tail.val;
}
if(idx>=si||idx<0){
System.out.println("invalid index");
return -1;
}
Node temp=head;
for(int i=0;i<=idx;i++){
temp=temp.next;
}
return temp.val;
}
void deleteAtHead() throws Error{
if(head==null){
throw new Error("list is empty");
}
head=head.next;
si--;
}
void deleteAtIndex(int idx)throws Error{
if(idx==0){
deleteAtHead();
return;
}
if(head==null){
throw new Error("list is empty");
}
if(idx<0||idx>si){
throw new Error("invalid index");
}
Node temp=head;
for(int i=1;i<idx;i++){
temp=temp.next;
}
if(temp.next==tail){
tail=temp;
}
temp.next=temp.next.next;
si--;
}
}
public class implementationLL {
public static void main(String[] args) {
SLL list=new SLL();
list.insertAtEnd(10);
list.insertAtEnd(20);
list.insertAtEnd(30);
list.insertAtHead(5);
// list.display();
//list.size();
// System.out.println(list.head.val);
// list.insert(2, 90);
list.display();
System.out.println(list.get(1));
// list.deleteAtHead();
// list.display();
list.deleteAtIndex(3);
list.display();
System.out.println(list.tail.val);
}
}