Skip to content

Commit a0e6bf6

Browse files
committed
Merge branch 'priyashuu-DeleteNodeInLL'
2 parents c1fc189 + 35281c2 commit a0e6bf6

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
* Algorithm Name:Delete Node in a Linked List .
3+
* Programming Language: Java
4+
* Category: Linked List
5+
* Difficulty Level: Medium
6+
*
7+
* Author: Priya Rani
8+
*
9+
* Algorithm Description:
10+
* There is a singly-linked list head and we want to delete a node node in it.
11+
12+
You are given the node to be deleted node. You will not be given access to the first node of head.
13+
14+
All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.
15+
16+
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
17+
18+
The value of the given node should not exist in the linked list.
19+
The number of nodes in the linked list should decrease by one.
20+
All the values before node should be in the same order.
21+
All the values after node should be in the same order.
22+
*
23+
* Time Complexity: O(1) -No traversal or loops are used, so the time complexity is O(1).
24+
* Space Complexity: O(1) - The algorithm uses only a constant amount of extra space (a few variables, no additional data structures).
25+
*/
26+
class ListNode {
27+
int val;
28+
ListNode next;
29+
ListNode(int x) {
30+
val = x;
31+
}
32+
}
33+
34+
public class DeleteNodeInLinkedList {
35+
public void deleteNode(ListNode node) {
36+
node.val = node.next.val;
37+
node.next = node.next.next;
38+
}
39+
40+
public static void main(String[] args) {
41+
42+
ListNode head = new ListNode(4);
43+
head.next = new ListNode(5);
44+
head.next.next = new ListNode(1);
45+
head.next.next.next = new ListNode(9);
46+
47+
DeleteNodeInLinkedList solution = new DeleteNodeInLinkedList();
48+
solution.deleteNode(head.next);
49+
50+
51+
ListNode current = head;
52+
while (current != null) {
53+
System.out.print(current.val + (current.next != null ? " -> " : ""));
54+
current = current.next;
55+
}
56+
}
57+
}
58+

0 commit comments

Comments
 (0)