-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_deletion2.java
80 lines (66 loc) · 1.79 KB
/
list_deletion2.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
//deleting a key at a given position
public class Posdel
{
Node head;
static class Node
{
Node next;
int data;
Node(int d)
{
data=d;
next=null;
}
}
//inserting a node in the front of list
public void insert(int element)
{
Node new_node=new Node(element);
new_node.next=head;
head=new_node;
}
public void delkey(int pos) //position of the key to be deleted
{
if(head==null)
return;
Node temp=head;
//if head is the key itself to be deleted
if(pos==0)
{
head=temp.next; //head is changed
return;
}
//we need to find the previous node so that position of pointers and all can be changed accordingly
for(int i=0; temp!=null&&i<pos-1; i++)
temp=temp.next;
//if position given is greater than the number of nodes
if(temp==null || temp.next==null)
return;
Node next=temp.next.next; //storing the pointer of the next node to be deleted
temp.next=next; //free the deleted node from the list
}
public void print()
{
Node n=head;
while(n!=null)
{
System.out.println(n.data+" ");
n=n.next;
}
}
public static void main(String args[])
{
Posdel pd=new Posdel();
pd.insert(10);
pd.insert(20);
pd.insert(30);
pd.insert(4);
pd.insert(50);
pd.insert(60);
System.out.println("Initially created list is ! ");
pd.print();
pd.delkey(2);
System.out.println("Now the list is ! ");
pd.print();
}
}