2024. 10. 25. 16:30ㆍ알고리즘/Leetcode
Solution
There is a singly linked list head, and we want to delete a node node in it.
You are given the node to be deleted node. You will not be given access to the first node of the head.
All the values of the linked list are unique, and it is guaranteed that the given node is not the last node in the linked list.
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
- The value of the given node should not exist in the linked list.
- The number of nodes in the linked list should decrease by one.
- All the values before node should be in the same order.
- All the values after node should be in the same order.
Custom testing:
- For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.
- We will build the linked list and pass the node to your function.
- The output will be the entire list after calling your function.
Examples
Example 1:

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.
Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Explanation
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
If we cannot access the head, it is impossible to change the pointer of the previous node in a single linked list; thus, we need to think about deleting the given node in a different way.
Whole concept: we copy the next node into the current node that will be deleted, and then skipping over the next node in the list, it has the effect of removing the node from the list without directly deleting it from memory.
Node: [4,5,1,9], Deleting node: 5
First Line
The given node of value has to be set to the next node of the value, and the list temporarily looks like [4, 1, 1, 9].
Second Line
Then, we set node.next to node.next.next, which skips over the original 1 node, making the list [4, 1, 9].
'알고리즘 > Leetcode' 카테고리의 다른 글
| Reverse Linked List (1) | 2024.11.07 |
|---|---|
| Remove Nth Node From End of List (4) | 2024.11.06 |
| String to Integer (atoi) (2) | 2024.10.22 |
| Longest Common Prefix (1) | 2024.10.16 |
| Implement strStr() (0) | 2024.10.14 |