-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0237_delete_node_in_a_linked_list.py
More file actions
90 lines (69 loc) · 1.97 KB
/
0237_delete_node_in_a_linked_list.py
File metadata and controls
90 lines (69 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""237. Delete Node in a Linked List
Medium
Example 1:
4 -> 5 -> 1 -> 9
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:
4 -> 5 -> 1 -> 9
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.
Constraints:
The number of the nodes in the given list is in the range [2, 1000].
-1000 <= Node.val <= 1000
The value of each node in the list is unique.
The node to be deleted is in the list and is not a tail node.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def listnode_2_str(head: ListNode) -> str:
result = ""
node = head
if node is None:
return ""
while node.next is not None:
result += "#" + str(node.val)
node = node.next
result += "#" + str(node.val)
return result
def list_2_listnode(lst: list) -> ListNode:
if len(lst) == 0:
return None
result = None
prev = None
lst.reverse()
for val in lst:
result = ListNode(val)
result.next = prev
prev = result
return result
def get_node_by_value(head: ListNode, v: int) -> ListNode:
node = head
while node is not None:
if node.val == v:
return node
else:
node = node.next
class Solution:
def deleteNode(self, node: ListNode):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
next_node: ListNode = node.next
node.val = next_node.val
node.next = next_node.next
sol = Solution()
head = list_2_listnode([4, 1, 5, 9])
node = get_node_by_value(head, 5)
sol.deleteNode(node)
actual = listnode_2_str(head)
expected = "#4#1#9"
assert actual == expected