Skip to content

Commit 9e78791

Browse files
Merge pull request #96 from niranjana687/patch-1
Delete a node from linked list
2 parents 17f9620 + a845950 commit 9e78791

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

LeetCode/DeleteNode.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// https://leetcode.com/problems/delete-node-in-a-linked-list/
2+
// O(n) solution
3+
4+
//Aproach: The question gives access to the node to be deleted instead of the head node. The node to be deleted will not
5+
//be a tail node hence we will set the value of the current node to be that of the next node and set the next of the
6+
//current node to the next of it's next. Simple and efficient solution, 0ms runtime.
7+
8+
public class DeleteNode {
9+
public class ListNode {
10+
int val;
11+
ListNode next;
12+
13+
ListNode(int x) {
14+
this.val = x;
15+
}
16+
}
17+
public void delete(ListNode node) {
18+
if (node.next.next != null) {
19+
node.val = node.next.val;
20+
node.next = node.next.next;
21+
} else if (node.next.next == null) {
22+
node.val = node.next.val;
23+
node.next = null;
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)