-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_linked_list.py
68 lines (58 loc) · 1.76 KB
/
custom_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
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def add_head(self, e):
node = Node(e)
node.next = self.head
self.head = node
self.size += 1
def add_tail(self,e):
ptr = self.head
while ptr.next is not None:
ptr = ptr.next
ptr.next = Node(e)
self.size += 1
def find_third_to_last(self):
ptr0 = self.head
ptr1 = self.head.next.next
while ptr1.next is not None:
ptr0 = ptr0.next
ptr1 = ptr1.next
return ptr0
def reverse(self):
previousNode = None
currentNode = self.head
nextNode = self.head.next
while currentNode is not None:
currentNode.next = previousNode
previousNode = currentNode
currentNode = nextNode
if nextNode is not None:
nextNode = nextNode.next
self.head = previousNode
def toString(self):
string = ""
ptr = self.head
while ptr is not None:
string += str(ptr.data) + " "
ptr = ptr.next
return string
class Node:
def __init__(self, data):
self.data = data
self.next = None
def main():
list = LinkedList()
list.add_head(3)
list.add_head(2)
list.add_head(1)
list.add_tail(4)
list.add_tail(5)
print("\nList before reversal: ", list.toString())
print("Third to last element:", list.find_third_to_last().data, "\n")
list.reverse()
print("List after reversal: ", list.toString())
print("Third to last element:", list.find_third_to_last().data, "\n")
if __name__ == "__main__":
main()