-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertafter__key_linkedlist.java
95 lines (85 loc) · 1.98 KB
/
insertafter__key_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
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 newnode=new Node(data);
if(head==null){
head=newnode;
return;
}
newnode.next=head;
head=newnode;
}
public void addlast(int data){
Node newnode=new Node(data);
if(head==null){
head=newnode;
return;
}
Node temp=head;
while(temp.next!=null){
temp=temp.next;
}
temp.next=newnode;
}
public void addafter(int data,int key){
Node newnode=new Node(data);
if(head==null){
head=newnode;
return;
}
Node temp=head;
while(temp!=null && temp.data!=key){
temp=temp.next;
}
if(temp==null){
System.out.println("Key not found");
return;
}
newnode.next=temp.next;
temp.next=newnode;
}
public void delete(int key){
if(head==null){
System.out.println("list is empty");
return;
}
if(head.data==key){
head=head.next;
return;
}
Node temp=head;
while(temp.next!=null && temp.next.data!=key){
temp=temp.next;
}
if(temp.next==null){
System.out.println("key is not found");
return;
}
temp.next=temp.next.next;
}
public void print(){
Node temp=head;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
System.out.println("null");
}
public static void main(String args[]){
LL list=new LL();
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
list.addlast(4);
list.print();
// list.addafter(4,6);
}
}