-
Notifications
You must be signed in to change notification settings - Fork 40
/
linked_list.py
63 lines (49 loc) · 1.35 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
#!/usr/bin/python
# Date: 2018-09-16
#
# Description:
# Implement linked list in python and perform basic operations.
#
# Reference:
# https://stackoverflow.com/questions/280243/python-linked-list
# https://www.codefellows.org/blog/implementing-a-singly-linked-list-in-python/
class Node:
def __init__(self, data):
self.data = data # Contains data
self.next = None # Contains reference to the next node
class LinkedList:
def __init__(self):
self.head = None
def add_node_at_start(self, data):
new_node = Node(data) # Create a new node
new_node.next = self.head # Link the new node to the 'previous' node.
self.head = new_node # Set the current node to the new one.
def add_node_at_end(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return None
node = self.head
while node.next:
node = node.next
node.next = new_node
def list_print(self):
"""
Prints the linked list.
"""
node = self.head
while node:
print(node.data)
node = node.next
linked_list = LinkedList()
linked_list.add_node_at_start(1)
linked_list.add_node_at_start(2)
linked_list.add_node_at_start(3)
linked_list.add_node_at_end(4)
linked_list.list_print()
# Output:
# -------
# 3
# 2
# 1
# 4