넘치게 채우기

[LeetCode] 237. Delete Node in a Linked List 본문

PS/LeetCode

[LeetCode] 237. Delete Node in a Linked List

riveroverflow 2024. 5. 5. 11:21
728x90
반응형

https://leetcode.com/problems/delete-node-in-a-linked-list/description/

leetcode - Delete Node in a Linked List

문제 유형 : 연결리스트

문제 난이도 : Medium

 

문제

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 head.

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.

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.

일반 연결리스트가 node부터 주어진다. head가 주어지진 않는다.

 

모든 값들은 중복이 없다.

맨 마지막 노드가 아니도록 보장되어있다.

노드를 삭제하시오.

삭제하라는 말은, 그것을 메모리에서 없애라는 말이 아닙니다.

 

대신, 노드의 개수가 1개 줄어야 하고, node의 값이 없어야 하고, node전후로의 순서는 같아야 합니다.

 

풀이

node의 다음 노드의 값을 가져온다.

맨 끝이 아님이 보장되어 있으므로, 무조건 유효한 값을 가져올 수 있다.

그 뒤, node의 next를 node의 next의 next로 한다.

 

즉, node의 next의 값을 가져온 다음, next를 없애는 것이다.

 

코드

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    void deleteNode(ListNode* node) {
        node -> val = node -> next -> val;
        node -> next = node -> next -> next;
    }
};

 

728x90
반응형