forked from msaimraz/Hacktoberfest_2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete_given_node_in_Linked_List.java
67 lines (65 loc) · 1.51 KB
/
Delete_given_node_in_Linked_List.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
import java.util.*;
class Node {
int num;
Node next;
Node(int a) {
num = a;
next = null;
}
}
class TUF{
//function to insert node at the end of the list
static Node insertNode(Node head,int val) {
Node newNode = new Node(val);
if(head == null) {
head = newNode;
return head;
}
Node temp = head;
while(temp.next != null) temp = temp.next;
temp.next = newNode;
return head;
}
//function to get reference of the node to delete
static Node getNode(Node head,int val) {
if(head==null)
return null;
while(head.num != val) head = head.next;
return head;
}
//delete function as per the question
static void deleteNode(Node t) {
if(t==null)
return;
t.num = t.next.num;
t.next = t.next.next;
return;
}
//printing the list function
static void printList(Node head) {
if(head==null)
return;
while(head.next!=null ) {
System.out.print(head.num+"->");
head = head.next;
}
System.out.println(head.num);
}
public static void main(String args[]) {
Node head = null;
//inserting node
head=insertNode(head,1);
head=insertNode(head,4);
head=insertNode(head,2);
head=insertNode(head,3);
//printing given list
System.out.println("Given Linked List: ");
printList(head);
Node t = getNode(head,2);
//delete node
deleteNode(t);
//list after deletion operation
System.out.println("Linked List after deletion: ");
printList(head);
}
}