-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_deletion1.java
93 lines (80 loc) · 2.18 KB
/
list_deletion1.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
//deleting a key from a singly linked list
import java.io.*;
public class Dellist
{
Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
}
//when a key is provided, this func deletes the first occurence of the key
public void firstdel(int key)
{
Node temp=head, prev=null; //head node stored
//if the first node is the key itself
if(temp!=null && temp.data==key)
{
head=temp.next; //head changed
return;
}
while(temp!=null && temp.data!=key)
{
prev=temp;
temp=temp.next;
}
//if key is absent
if(temp==null)
return;
prev.next=temp.next;
}
public void push(int element)
{
Node n = new Node(element);
n.next=head;
head=n;
}
public void print()
{
Node no=head;
while(no!=null)
{
System.out.print(no.data+" ");
no=no.next;
}
}
public static void main(String args[])throws IOException
{
Dellist dl=new Dellist();
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// System.out.println("How many elements u wanna put into the list?");
// int n = Integer.parseInt(br.readLine());
// for(int i=0;i<n;i++)
// {
// System.out.println("Continue");
// dl.push(i);
// }
// System.out.println("The list is: ");
// dl.print();
// System.out.println("Now enter the element u wanna remove from the list!!");
// int nu=Integer.parseInt(br.readLine());
// dl.firstdel(nu);
// System.out.println("After deleting the final list is :");
// dl.print();
dl.push(1);
dl.push(5);
dl.push(8);
dl.push(6);
dl.push(9);
System.out.println("Created list");
dl.print();
dl.firstdel(8);
System.out.println("New list");
dl.print();
}
}