Skip to content

Commit 799fcc8

Browse files
committed
delete a node from singly linked list with only access to the node
1 parent 848f633 commit 799fcc8

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

DeleteNode.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# coding:utf-8
2+
__author__ = 'devin'
3+
4+
# Definition for singly-linked list.
5+
# class ListNode(object):
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.next = None
9+
10+
11+
class Solution(object):
12+
def deleteNode(self, node):
13+
"""
14+
:type node: ListNode
15+
:rtype: void Do not return anything, modify node in-place instead.
16+
"""
17+
p1 = node
18+
p2 = node.next
19+
while p2 is not None:
20+
p1.val = p2.val
21+
if p2.next is None:
22+
p1.next = None
23+
break
24+
p1 = p2
25+
p2 = p2.next
26+
27+
class ListNode(object):
28+
def __init__(self, x):
29+
self.val = x
30+
self.next = None
31+
32+
if __name__ == '__main__':
33+
node = ListNode(1)
34+
p = node
35+
for i in range(2, 5):
36+
temp = ListNode(i)
37+
p.next = temp
38+
p = p.next
39+
40+
p = node
41+
while p is not None:
42+
print p.val
43+
p = p.next
44+
45+
s = Solution()
46+
s.deleteNode(node)
47+
p = node
48+
while p is not None:
49+
print p.val
50+
p = p.next
51+
52+
53+
54+
55+
56+

0 commit comments

Comments
 (0)