Skip to content

Commit e31112a

Browse files
committed
Delete Node in a Linked List/ Product of Array Except Self
1 parent e083213 commit e31112a

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Write a function to delete a node (except the tail) in a singly linked list,
3+
given only access to that node.
4+
5+
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node
6+
with value 3, the linked list should become 1 -> 2 -> 4 after calling your
7+
function.
8+
'''
9+
10+
# Definition for singly-linked list.
11+
class ListNode(object):
12+
def __init__(self, x):
13+
self.val = x
14+
self.next = None
15+
16+
class Solution(object):
17+
def deleteNode(self, node):
18+
"""
19+
:type node: ListNode
20+
:rtype: void Do not return anything, modify node in-place instead.
21+
"""
22+
node.val = node.next.val
23+
node.next = node.next.next
24+
25+
26+
if __name__=="__main__":
27+
n1 = ListNode(1)
28+
n2 = ListNode(2)
29+
n3 = ListNode(3)
30+
n4 = ListNode(4)
31+
n1.next = n2
32+
n2.next = n3
33+
n3.next = n4
34+
Solution().deleteNode(n3)
35+
assert n2.next.val == 4
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'''
2+
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
3+
4+
Solve it without division and in O(n).
5+
6+
For example, given [1,2,3,4], return [24,12,8,6].
7+
8+
Follow up:
9+
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
10+
'''
11+
12+
class Solution(object):
13+
def productExceptSelf(self, nums):
14+
"""
15+
:type nums: List[int]
16+
:rtype: List[int]
17+
"""
18+
n = len(nums)
19+
result = [1] * n
20+
for i in range(1, n):
21+
result[i] = result[i - 1] * nums[i - 1]
22+
temp = 1
23+
for i in range(n - 1, -1, -1):
24+
result[i] *= temp
25+
temp *= nums[i]
26+
return result
27+
28+
29+
if __name__ == "__main__":
30+
assert Solution().productExceptSelf([1, 2, 3, 4]) == [24, 12, 8, 6]

0 commit comments

Comments
 (0)