Leetcode question 237, delete a node in a linked list, an easy question
It is said to be an easy question. What bothers me is that I do not know how to implement it on my own computer. I need a full example. Moreover, Leetcode provides a list, not a linked list. Do I have to write my own linked list?
This is from the original question:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
I do not have the solution even as a premium member, and this is a widely accepted solution I found on the web:
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
if not node:
return
node.val = node.next.val
node.next = node.next.next
Could anyone provide me with a full example that I can run on my own computer? Do I need a data structure LinkedList along with ListNode? Thank you very much!
What follows is an incomplete solution…
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
if not node:
return
node.val = node.next.val
node.next = node.next.next
# How should I initialize a solution class?
# mysol = Solution(...)??
## How should I create a list like the original question?
#
e1 = ListNode(4)
e2 = ListNode(5)
e3 = ListNode(1)
e4 = ListNode(9)
e1.next = e2
e2.next = e3
e3.next = e4