/
linked_list.py
97 lines (76 loc) · 2.02 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def append(self, value):
node = Node(value)
if not self.head:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
self.length += 1
def prepend(self, value):
node = Node(value)
if not self.head:
self.head = node
self.tail = node
else:
node.next = self.head
self.head = node
self.length += 1
def contains(self, value):
current = self.head
while(current):
if current.value == value:
return True
current = current.next
return False
def remove(self, value):
current = self.head
if current.value == value:
self.head = self.head.next
self.length -= 1
return
while(current.next):
if current.next.value == value:
break
current = current.next
if not current.next:
return
if (current.next == self.tail):
self.tail = current
current.next = current.next.next
self.length -= 1
def remove_at(self, position):
if position < 0 or position > self.length:
return
current = self.head
# finish
pass
def front(self):
return self.head.value if self.head else None
def back(self):
return self.tail.value if self.tail else None
class Node:
def __init__(self, value):
self.value = value
self.next = None
# ll = LinkedList()
# ll.append(4)
# ll.append(5)
# ll.append(6)
# ll.append(7)
# ll.append(8)
# ll.remove(8)
# print(ll.contains(6))
# print(ll.contains(8))
# print(ll.back())
# print(ll.front())
# print(ll.back())
# print(ll.prepend(1))
# print(ll.front())
# print(ll.contains(5))
# print(ll.contains(6))