-
Notifications
You must be signed in to change notification settings - Fork 43
/
singly_linked.py
75 lines (52 loc) · 1.26 KB
/
singly_linked.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Node:
def __init__(self, x):
self.val = x
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.cnt = 0
def addHead(self, x):
node = Node(x)
node.next = self.head
self.head = node
self.cnt += 1
def addTail(self, x):
node = Node(x)
if self.head is None:
self.head = node
else:
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = node
self.cnt += 1
def removeHead(self):
if self.head is None:
return
self.head = self.head.next
self.cnt -= 1
def removeTail(self):
if self.head is None:
return
cur = self.head
prev = cur
while cur.next is not None:
prev = cur
cur = cur.next
prev.next = None
self.cnt -= 1
def size(self):
return self.cnt
def printForward(head):
if head is None:
return
print(head.val)
while head.next is not None:
head = head.next
print(head.val)
def printReverse(head):
if head is None:
return
printReverse(head.next)
print(head.val)