-
Notifications
You must be signed in to change notification settings - Fork 0
/
linklist.py
59 lines (53 loc) · 1.48 KB
/
linklist.py
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
from node import *
class LinkList(object):
def __init__(self):
self.head = None
def search(self, key):
dummy = ListNode(-1, -1)
curr = dummy
curr.next = self.head
while curr.next:
if curr.next.kv.key == key:
return curr.next.kv.val
else:
curr = curr.next
return -1
def insert(self, key, val):
cnt = 0
dummy = ListNode(-1, -1)
curr = dummy
curr.next = self.head
isExisted = False
while curr.next:
cnt += 1
if curr.next.kv.key == key:
curr.next.kv.val = val
isExisted = True
break
else:
curr = curr.next
if not isExisted:
node = ListNode(key, val)
curr.next = node
self.head = dummy.next
return dummy.next, cnt
def remove(self, key):
dummy = ListNode(-1, -1)
curr = dummy
curr.next = self.head
while curr.next:
if curr.next.kv.key == key:
curr.next = curr.next.next
break
else:
curr = curr.next
self.head = dummy.next
return dummy.next
def prompt(self):
if self.head is None:
print("")
return
node = self.head
while node is not None:
print('(', node.kv.key, ',', node.kv.val, ')')
node = node.next