-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicssll.java
More file actions
125 lines (117 loc) · 3.13 KB
/
Copy pathbasicssll.java
File metadata and controls
125 lines (117 loc) · 3.13 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
class basicssll {
public static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
public static void display(Node a) {
Node temp = a;
if (temp.next == null) {
System.out.println(temp.data);
return;
}
System.out.print(temp.data + "->");
display(temp.next);
}
public static class LinkedList {
Node head = null;
Node tail = null;
int size=0;
void insertAtEnd(int val) {
Node temp = new Node(val);
if (head == null) {
head = tail = temp;
size++;
} else {
tail.next = temp;
tail = temp;
size++;
}
}
void insertAtFirst(int val){
Node temp=new Node(val);
if(head==null && tail==null){
head=tail=temp;
size++;
}else{
temp.next=head;
head=temp;
size++;
}
}
void insertAt(int idx,int val){
Node temp=new Node(val);
Node t=head;
if(idx==0){
insertAtFirst(val);
return;
}
if(idx==size){
insertAtEnd(val);
return;
}
if(idx>size || idx<0){
System.out.println("wrong index");
return;
}
for(int i=1;i<idx;i++){
t=t.next;
}
temp.next=t.next;
t.next=temp;
}
int getAt(int idx){
Node temp=head;
if(idx>size||idx<0){
System.out.println("wrong index ");
return -1;
}
if(idx==0){
return temp.data;
}else{
for(int i=1;i<=idx;i++){
temp=temp.next;
}
}
return temp.data;
}
void deleteAtIndex(int idx){
Node temp=head;
if(idx>size||idx<0){
System.out.println("wrong index");
return;
}
for(int i=0;i<idx-1;i++){
temp=temp.next;
}
temp.next=temp.next.next;
}
void display() {
Node t = head;
if (t == null) {
System.out.println("List is empty!");
return;
}
System.out.print("Linked list: ");
while (t != null) {
System.out.print(t.data + " -> ");
t = t.next;
}
System.out.println("null");
}
}
public static void main(String args[]) {
LinkedList l1 = new LinkedList();
l1.insertAtEnd(5);
l1.insertAtEnd(10);
l1.insertAtEnd(15);
l1.insertAtFirst(4);
l1.insertAtFirst(2);
l1.insertAt(3,00);
l1.display();
l1.deleteAtIndex(3);
l1.display(); // should print: Linked list: 5 -> 10 -> 15 -> null
}
}