-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
79 lines (71 loc) · 2.17 KB
/
Copy pathlinked_list.py
File metadata and controls
79 lines (71 loc) · 2.17 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
77
78
79
class Node():
def __init__(self, val, next = None):
self.val = val
self.next = next
class LinkedList():
def __init__(self):
self.head = None
def size(self):
current = self.head
size = 0
while current.next:
current.next
size += 1
return size
def prepend(self, data):
new_node = Node(data)
if self.head == None:
new_node.next = None
self.head = new_node
return
new_node.next = self.head
self.head = new_node
def append(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def removebeginning(self):
if self.head == None:
return print("Linked List is empty!")
self.head = self.head.next
def removeend(self):
if self.head == None:
return print("Linked List is empty!")
if self.head.next == None:
self.head = None
return
point = self.head
point_two = self.head.next
while point_two.next:
point = point.next
point_two = point_two.next
point.next = None
def removeat(self, index):
if self.head is None:
print("Linked List is empty!")
return
if index == 0:
self.head = self.head.next
return
current = self.head
for i in range(index - 1):
if current.next is None:
print("Index out of bounds!")
return
current = current.next
if current.next is None:
print("Index out of bounds!")
return
current.next = current.next.next
def insert(self, data, index):
new_node = Node(data)
current = self.head
for i in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node