본문 바로가기
LeetCode/Top Interview Q. - Easy

LeetCode. Delete Node in a Linked List [Linked List]

by 벤진[Benzene] 2020. 6. 3.

Problem:

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:

 

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.

 

-Summary-

1. Change current node's value to the next node value.

2. Change current node's next direction to next next.

 

Leetcode에 있는 discussion 에서의 그래픽이 이해하는데 도움이 된다.

leetcode.com/problems/delete-node-in-a-linked-list/discuss/354949/Python3-1-line-with-explanation

class Solution(object):
    def deleteNode(self, node):
        """
        1  ->  2 -> 3       -> 4
               ^    ^
               |    |
              node  node.next
                 ______________
                /              \
         1  ->  3   3           4
               ^    ^           ^
               |    |           |
              node  node.next   node.next.next
              
                 ______________
                /              \
         1  ->  3   3         4
               ^    ^           ^
               |    |           |
              node  node.next   node.next.next
			  
	    1 ->3 ->4
        """
        node.val , node.next = node.next.val, node.next.next

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글