Skip to content

Commit

Permalink
add tail to linked list
Browse files Browse the repository at this point in the history
  • Loading branch information
QiLinXue committed Mar 16, 2023
1 parent 304b124 commit 3fe8dab
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions data_structures/linkedlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def __str__(self):
class LinkedList:
def __init__(self):
self.head = None
self.tail = None

def get_i(self, i):
# return the value at index i
Expand All @@ -21,16 +22,13 @@ def append(self, value):
'''Add a new node with the value value to the end of the list'''
# Create a new node
new_node = Node(value)
print(new_node)


if self.head == None:
self.head = new_node
else:
# Find the last node
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
self.tail = new_node

self.tail.next = new_node
self.tail = new_node

def insert(self, value, i):
'''Insert a node with the value value at index i'''
Expand All @@ -39,12 +37,16 @@ def insert(self, value, i):
if i == 0:
new_node.next = self.head
self.head = new_node

else:
cur = self.head
for j in range(i-1):
cur = cur.next
new_node.next = cur.next
cur.next = new_node

if new_node.next == None:
self.tail = new_node

def __str__(self):
cur = self.head
Expand Down

0 comments on commit 3fe8dab

Please sign in to comment.