-
Notifications
You must be signed in to change notification settings - Fork 0
/
237. Delete Node in a Linked List
39 lines (33 loc) · 1.12 KB
/
237. Delete Node in a Linked List
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
/*
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
*/
/*
Idea: Swap with Next Node.
Since we do not have access to the node before the one we want to delete,we cannot modify the next pointer of that nodein any way.
We have to replace the value of the node we want to delete with the value in the node after it, and then delete the node after it.
*/
class Solution {
public void deleteNode(ListNode node) {
while (node.next != null){
ListNode next = node.next;
node.val = next.val;
if(next.next == null){
node.next = null;
}else {
node = next;
}
}
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/