Skip to content

Commit 640056f

Browse files
delete node in a linked list
1 parent 010064e commit 640056f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package easy;
2+
3+
import classes.ListNode;
4+
5+
/**237. Delete Node in a Linked List QuestionEditorial Solution My Submissions
6+
Total Accepted: 96741
7+
Total Submissions: 218247
8+
Difficulty: Easy
9+
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
10+
11+
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
12+
13+
Hide Company Tags Adobe Apple Microsoft
14+
Hide Tags Linked List
15+
Hide Similar Problems (E) Remove Linked List Elements
16+
*/
17+
public class DeleteNodeInALinkedList {
18+
19+
/**We're not really deleting the node, but we're overwriting this node's value with its successor's value,
20+
* and then append its successor's successor to its new successor.
21+
*
22+
* In graph, it's like this:
23+
* Given this list: 1->2->3->4->null and only access to this to-be-deleted node 3
24+
* we overwrite 3 with 4, and then assign null to be 4's next.*/
25+
public void deleteNode(ListNode node) {
26+
node.val = node.next.val;
27+
node.next = node.next.next;
28+
}
29+
30+
}

0 commit comments

Comments
 (0)