-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDelete_node.java
79 lines (78 loc) · 1.64 KB
/
Delete_node.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
package Programs2;
import java.util.*;
class Node<T> {
T data;
Node<T> next;
Node(T d) {
data = d;
}
}
public class Delete_node {
static Node createLinkedList() {
Scanner s = new Scanner(System.in);
System.out.print("Enter data : ");
int data = s.nextInt();
Node head = null;
Node temp=null;
while (data != -1) {
Node node = new Node(data);
if (head == null) {
head = node;
temp=head;
} else {
temp.next=node;
temp=temp.next;
}
System.out.print("Enter next data : ");
data = s.nextInt();
}
return head;
}
static void display(Node head)
{
Node temp=head;
while(temp!=null){
System.out.print(temp.data+" ");
temp= temp.next;
}
}
public static Node<Integer> deleteIthNode(Node<Integer> head, int i) //Function to delete a node
{
Node temp=head,temp2=head;
int count=0,c1=0;
while(temp2!=null)
{
c1++;
temp2=temp2.next;
}
if(i==0)
{
head=head.next;
return head;
}
else if(i>0&&i<c1)
{
while(count<i-1)
{
temp=temp.next;
count++;
}
temp.next=temp.next.next;
}
return head;
}
public static void main(String[] args) {
Node head = createLinkedList();
Scanner s=new Scanner(System.in);
Node temp = head;
System.out.println();
System.out.print("Linked List formed is : ");
display(temp);
System.out.println();
System.out.print("Enter the Position from where you want to delete the node : ");
int pos=s.nextInt();
head=deleteIthNode(temp, pos-1);
System.out.print("Linked List after deletion of a node from position "+pos+" is : ");
display(head);
}
}