내 맘대로 알고리즘/LeetCode 2020 June

June LeetCoding Challenge[Day2] - Delete Node in a Linked List

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:

 

0. 알고리즘을 해결하기 위해서 생각한 방법

 

 - 해당 문제는 현재 노드의 삭제 로직을 구현하는 문제입니다.

 - node.next = node.next.next; 를 통해서, 다음다음 노드를 가리키게 합니다.

 - node.val = node.next.val; 을 통해서, 현재 value를 없애주고, 다음 value를 덮어쓰게 되면서 현재 노드는 기존의 다다음노드를 가리키고, 현재 노드가 다음 노드의 값을 가져오면서, 한 칸씩 당겨집니다.

 

2. 알고리즘 작성 중, 어려운 점 & 깨달은 점

 

 - 없음

 

3. 내가 작성한 알고리즘

 

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        if (node.next != null) {
			node.val = node.next.val;
			node.next = node.next.next;
		}
    }
}

 

4. 결과

 

 

문제 : https://leetcode.com/explore/featured/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3348/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com