-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLL.java
More file actions
107 lines (101 loc) · 2.49 KB
/
LL.java
File metadata and controls
107 lines (101 loc) · 2.49 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
public class LL{
Node head;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
public void addfirst(int data){
Node new_node=new Node(data);
if(head==null){
head=new_node;
return;
}
new_node.next=head;
head=new_node;
}
public void addlast(int data){
Node new_node=new Node(data);
if(head==null){
head=new_node;
return;
}
Node temp=head;
while (temp.next!=null) {
temp=temp.next;
}
temp.next=new_node;
new_node.next=null;
}
public void deletefirst(){
if(head==null){
System.out.println("The list is empty");
return;
}
head=head.next;
}
public void deleteLast(){
Node last=head.next;
Node secondlast=head;
while (last.next!=null) {
last=last.next;
secondlast=secondlast.next;
}
secondlast.next=null;
}
public void addindex(int index,int data){
Node new_node=new Node(data);
if(head==null){
head=new_node;
return;
}
Node temp=head;
for(int i=1;i<index;i++){
temp=temp.next;
}
new_node.next=temp.next;
temp.next=new_node;
}
public void delindex(int index){
if(head==null){
System.out.println("The list is empty");
return;
}
Node last=head.next;
Node second=head;
for(int i=1;i<index;i++){
last=last.next;
second=second.next;
}
second.next=last.next;
}
public void display(){
if(head==null){
System.out.println("List is empty");
}
Node temp=head;
while (temp!=null) {
System.out.print(temp.data + "->");
temp=temp.next;
}
System.out.println("END");
}
public static void main(String[] args) {
LL list=new LL();
list.addfirst(5);
list.addfirst(6);
list.addfirst(10);
list.addfirst(8);
list.delindex(2);
// list.display();
// list.deletefirst();
// list.display();
// list.deleteLast();
// list.display();
list.addindex(3, 7);
list.display();
}
}