-
Notifications
You must be signed in to change notification settings - Fork 2
/
linked_list.py
75 lines (56 loc) · 1.08 KB
/
linked_list.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:
data = 0
next = None
def __init__(self, data):
self.data = data
def append(self, data):
tailnode = Node(data)
n = self
while n.next is not None:
n = n.next
n.next = tailnode
class LinkedList:
head = None
def __init__(self):
self.head = None
def __init__(self, from_list):
if from_list is None:
self.head = None
return
for data in from_list:
self.append(data)
def append(self, data):
if self.head is None:
self.head = Node(data)
else:
self.head.append(data)
def remove(self, data):
if self.head is None:
return None
if self.head.data == data:
self.head = self.head.next
else:
p = self.head
n = self.head.next
while n is not None:
if n.data == data:
p.next = n.next
break
else:
p = n
n = n.next
return self.head
def to_string(self):
s = '['
n = self.head
while n is not None:
s = s + str(n.data)
if n.next is not None:
s = s + ', '
n = n.next
s = s + ']'
return s
def output(self):
import sys
sys.stdout.write(self.to_string())
print ''