-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
76 lines (58 loc) · 2.4 KB
/
Copy pathlinked_list.py
File metadata and controls
76 lines (58 loc) · 2.4 KB
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
"""
Implements the Linked List class and Node class so that
the file linked_list_friend.py can import this file and use those classes.
"""
class LinkedList():
def __init__(self):
"""Instantiates a Linked List object with its head attribute set
to None.
Parameters: None.
Returns: None."""
self._head = None
def add(self, node):
"""Adds a node to the beginning of the Linked List.
Parameters: node is a Node object.
Returns: None."""
node._next = self._head
self._head = node
def is_empty(self):
"""Returns whether or not the Linked List is empty or not.
Parameters: None.
Returns: A boolean depending on whether or not the list is empty."""
return self._head == None
def sort(self):
"""Sorts the names in a Linked List by alphabetical order.
Parameters: None.
Returns: None."""
ll = LinkedList()
if self._head != None and self._head._next != None:
while self._head != None:
current = self._head
self._head = current._next
if ll._head == None or ll._head._name >= current._name:
ll.add(current)
else:
current_2 = ll._head
while current_2 != None:
if current_2._next == None or \
current_2._next._name >= current._name:
current._next = current_2._next
current_2._next = current
break
current_2 = current_2._next
self._head = ll._head
class Node():
def __init__(self, name):
"""Instantiates a Node object with its name attribute set to name,
a friends attribute instantiating a Linked List object, and its
next attribute set to None.
Parameters: name is a string.
Returns: None."""
self._name = name
self._friends = LinkedList()
self._next = None
def add_friend(self, node):
"""Adds a node to the friends attribute of a Node object.
Parameters: node is the node you want to add to the friends attribute.
Returns: None."""
self._friends.add(node)