0% found this document useful (0 votes)
2 views

LinkedList(1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

LinkedList(1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Linked List: Constructor

You are tasked with implementing a basic data structure: a singly linked list.

To accomplish this, you will create two classes, Node and LinkedList.

The Node class will represent an individual node within the linked list, while
the LinkedList class will manage the overall list structure.

Your implementation should satisfy the following requirements:

1. Create a Node class with the following features:


a. A constructor that takes a value as an argument and initializes
the value attribute of the node.
b. A next attribute, initialized to None, which will store a
reference to the next node in the list.
2. Create a LinkedList class with the following features:
a. A constructor that takes a value as an argument, creates a new
Node with that value, and initializes the head and tail
attributes of the linked list to point to the new node.
b. A length attribute, initialized to 1, which represents the current
number of nodes in the list.
class Node:

def __init__(self,value):

self.value=value

self.next=None

class LinkedList:

def __init__(self,value):

new_node=Node(value)

self.head=new_node

self.tail=new_node

self.length=1

my_linked_list = LinkedList(4)

print('Head:', my_linked_list.head.value)

print('Tail:', my_linked_list.tail.value)

print('Length:', my_linked_list.length)
Linked List: Print List

Implement a method print_list(self) that prints the linked list's


elements, one per line.

class Node:
def __init__(self, value):
self.value = value
self.next = None

class LinkedList:
def __init__(self, value):
new_node = Node(value)
self.head = new_node
self.tail = new_node
self.length = 1

def print_list(self):
temp=self.head
while temp is not None:
print(temp.value)
temp=temp.next

def make_empty(self):
self.head = None
self.tail = None
self.length = 0
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1

my_linked_list = LinkedList(1)
my_linked_list.append(2)
my_linked_list.append(3)

my_linked_list.print_list()

EXPECTED OUTPUT:
----------------
1
2
3
Linked List: Append
Implement the append method for the LinkedList class.

The append method should add a new node with a given value to the end of the linked
list, updating the tail attribute and the length attribute accordingly.

Keep in mind the following requirements:

1. The method should handle the cases where the list is empty and where the list
already has one or more nodes.
2. The method should create a new node with the given value and add it to the end
of the list.
3. The method should update the tail attribute of the LinkedList correctly.
4. The method should update the length attribute of the LinkedList to reflect the
addition of the new node.

class Node:

def __init__(self, value):

self.value = value

self.next = None

class LinkedList:

def __init__(self, value):

new_node = Node(value)

self.head = new_node

self.tail = new_node

self.length = 1
def print_list(self):

temp = self.head

while temp is not None:

print(temp.value)

temp = temp.next

def make_empty(self):

self.head = None

self.tail = None

self.length = 0

def append(self, value):

new_node = Node(value)

if self.head==None:

self.head=new_node

self.tail=new_node

else:

self.tail.next=new_node

self.tail=new_node

self.length += 1

return True
my_linked_list = LinkedList(1)

my_linked_list.make_empty()

my_linked_list.append(1)

my_linked_list.append(2)

print('Head:', my_linked_list.head.value)

print('Tail:', my_linked_list.tail.value)

print('Length:', my_linked_list.length, '\n')

print('Linked List:')

my_linked_list.print_list()

EXPECTED OUTPUT:

----------------

Head: 1

Tail: 2

Length: 2

Linked List:

2
Linked List: Pop

Your task is to implement the pop method for the LinkedList class.

The pop method should remove the last node (tail) from the linked list and
return the removed node. If the list is empty, the method should return
None.

After the last node is removed, the second-to-last node should become
the new tail of the list.

Additionally, if the list becomes empty after the pop operation, both the
head and tail attributes should be set to None.

Keep in mind the following requirements:

1. The method should handle the cases where the list is empty, has
only one node, or has multiple nodes.
2. The method should update the tail attribute of the LinkedList
correctly.
3. The method should update the length attribute of the LinkedList to
reflect the removal of the node.
4. The method should either return the removed node or None if the list
is empty.
Algorithm for pop Function in a Linked List

1. Check if the list is empty:


○ If self.length is 0:
■ Return None, as there is no node to pop.
2. Initialize Pointers:
○ Set temp and prev pointers to the head of the list.
○ temp will traverse the list to find the last node.
○ prev will follow temp to keep track of the node just before the last node.
3. Traverse to the End of the List:
○ While temp.next is not None (meaning temp has not yet reached the last
node):
■ Update prev to temp.
■ Move temp to temp.next.
4. Update Tail and Remove Last Node:
○ Set self.tail to prev, making the previous node the new tail.
○ Set self.tail.next to None, effectively removing the last node from the list.
○ Decrement self.length by 1.
5. Check if List is Now Empty:
○ If self.length is now 0 (meaning the list had only one node originally):
■ Set self.head and self.tail to None to make the list empty.
6. Return the Removed Node:
○ Return temp, which holds the reference to the removed last node.

def pop(self):
if self.length == 0:
return None
temp=self.head
prev=self.head
while temp.next is not None:
prev=temp
temp=temp.next
self.tail=prev
self.tail.next=None
self.length-=1
if self.length==0:
self.head=None
self.tail=None
return temp.value
Linked List:: Prepend
Implement the prepend method for the LinkedList class.

The prepend method should add a new node with a given value to the
beginning of the linked list, updating the head attribute and the length
attribute accordingly.

Keep in mind the following requirements:

1. The method should handle the cases where the list is empty and
where the list already has one or more nodes.
2. The method should create a new node with the given value and
add it to the beginning of the list.
3. The method should update the head attribute of the LinkedList
correctly.
4. The method should update the length attribute of the LinkedList
to reflect the addition of the new node.
5. The method should return True if the operation is successful.

Algorithm for prepend Function

1. Create a New Node:


○ Initialize new_node with the given value.
2. Check if List is Empty:
○ If self.length is 0:
■ Set both self.head and self.tail to new_node, as
this is the first node in the list.
○ Else:
■ Set new_node.next to the current head.
■ Update self.head to new_node.
3. Update Length:
○ Increment self.length by 1.
4. Return Success:
○ Return True to indicate the operation was successful.

def prepend(self,value):

new_node=Node(value)

if self.length==0:

self.head=new_node

self.tail=new_node

else:

new_node.next=self.head

self.head=new_node

self.length+=1

return True
LL: Pop First
Implement the pop_first method for the LinkedList class.

The pop_first method should remove the first node (the head) from
the linked list, update the head attribute and the length attribute
accordingly, and return the removed node.

Keep in mind the following requirements:

1. The method should handle the cases where the list is empty and
where the list has one or more nodes.
2. The method should save a reference to the current head node
before updating the head attribute.
3. The method should update the head attribute to the second
node in the list.
4. The method should disconnect the removed node from the list
by setting its next attribute to None.
5. The method should update the length attribute of the LinkedList
to reflect the removal of the node.
6. If the list becomes empty after removing the node, the method
should set the tail attribute of the LinkedList to None.
7. The method should return the removed node, or None if the list
is empty.
Algorithm for pop_first Function

1. Check if List is Empty:


○ If self.length is 0:
■ Return None, as there is no node to pop.
2. Store Current Head:
○ Set temp to self.head (the current first node).
3. Update Head:
○ Move self.head to self.head.next to remove the first
node from the list.
4. Disconnect Popped Node:
○ Set temp.next to None to fully detach it from the list.
5. Update Length:
○ Decrement self.length by 1.
6. Check if List is Now Empty:
○ If self.length is 0 after the decrement:
■ Set self.tail to None, as the list is now empty.
7. Return Value of Popped Node:
○ Return temp.value, the value of the removed node.
def pop_first(self):

if self.length==0:

return None

temp=self.head

self.head=self.head.next

temp.next=None

self.length-=1

if self.length ==0:

self.tail=None

return temp.value
LinkedList: Get

Implement the get method for the LinkedList class.

The get method should take an integer index as a parameter and


return a pointer to the node at the specified index in the linked
list.

If the index is out of bounds (less than 0 or greater than or equal


to the length of the list), the method should return None.

Keep in mind the following requirements:

1. The method should handle the cases where the index is out
of bounds.
2. The method should start at the head of the list and traverse
the list using the next attribute of the nodes.
3. The method should stop traversing the list when it reaches
the specified index and return the node at that position.
4. If the index is out of bounds, the method should return
None.
Algorithm for get Function

1. Check Index Validity:


○ If index is less than 0 or greater than or equal to
self.length, return None (index is out of bounds).
2. Initialize a Temporary Pointer:
○ Set temp to self.head to start traversal from the
beginning of the list.
3. Traverse to the Target Node:
○ For each position from 0 up to index - 1, update
temp to temp.next to move one node forward.
4. Return the Target Node:
○ Return temp, the node at the specified index.

def get(self,index):

if index<0 or index >=self.length:

return None

temp=self.head

for _ in range(index):

temp=temp.next

return temp
LinkedList : Set

Implement the set_value method for the LinkedList class.

The set_value method should take an integer index and a value as


parameters and update the value of the node at the specified index in the
linked list.

If the index is out of bounds, the method should return False. If the value
is successfully updated, the method should return True.

Keep in mind the following requirements:

1. The method should utilize the get method to find the node at the
specified index.
2. The method should update the value of the node if the node is
found.
3. The method should return True if the value is successfully updated.
4. If the node is not found (i.e., the index is out of bounds), the method
should return False.
Algorithm for set_value Function

1. Retrieve Node at Target Index:


○ Call self.get(index) to get the node at the specified
index.
○ Store the result in temp.
2. Check if Node Exists:
○ If temp is None (i.e., index is out of bounds or the node does
not exist), return False.
3. Set New Value:
○ If temp is not None, set temp.value to the specified value.
4. Return Success:
○ Return True to indicate the value was successfully set.

def set_value(self,index,value):

temp=self.get(index)

if temp:

temp.value=value

return True

return False
LinkedList: Insert

Implement the insert method for the LinkedList class.

Method signature: def insert(self, index, value):

The insert method should take an integer index and a value as parameters
and insert a new node with the given value at the specified index in the
linked list.

If the index is out of bounds, the method should return False. If the new
node is successfully inserted, the method should return True.

Keep in mind the following requirements:

1. The method should handle edge cases, such as inserting a new node
at the beginning or end of the list.
2. The method should utilize the prepend, append, and get methods for
handling these edge cases.
3. The method should create a new node with the given value and
insert it at the specified index.
4. The method should update the next attribute of the previous node to
point to the new node.
5. The method should increment the length attribute of the LinkedList
class.
6. The method should return True if the new node is successfully
inserted.
7. If the index is out of bounds, the method should return False.
Algorithm for insert Function

1. Check Index Validity:


○ If index is less than 0 or greater than self.length:
■ Return False (index is out of bounds).
2. Handle Special Cases:
○ If index is 0:
■ Call self.prepend(value) to insert at the beginning and return the
result.
○ If index is equal to self.length:
■ Call self.append(value) to insert at the end and return the result.
3. Insert in the Middle:
○ Create a new node new_node with the given value.
○ Call self.get(index - 1) to get the node just before the desired index,
and store it in temp.
○ Set new_node.next to temp.next (linking the new node to the next node in
the list).
○ Set temp.next to new_node (inserting the new node in the desired position).
4. Update Length:
○ Increment self.length by 1 to reflect the insertion.
5. Return Success:
○ Return True to indicate the node was successfully inserted.

def insert(self,index,value):
if index<0 or index > self.length:
return False
if index==0:
return self.prepend(value)

if index==self.length:
return self.append(value)
new_node=Node(value)
temp=self.get(index-1)
new_node.next=temp.next
temp.next=new_node
self.length+=1
return True
LinkedList: Remove

Implement the remove method for the LinkedList class.

The remove method should take an integer index as a parameter and remove the node
at the specified index in the linked list, returning the removed node.

If the index is out of bounds, the method should return None.

Keep in mind the following requirements:

1. The method should handle edge cases, such as removing a node at the
beginning or end of the list.
2. The method should utilize the pop_first() and pop() methods for handling
these edge cases.
3. The method should use the get() method to find the node previous to the one
to be removed.
4. The method should update the next attribute of the previous node to point to
the node after the removed one.
5. The method should decrement the length attribute of the LinkedList class.
6. The method should return the removed node if the removal is successful.
7. If the index is out of bounds, the method should return None.
Algorithm for remove Function

1. Check Index Validity:


○ If index is less than 0 or greater than or equal to self.length, return
None (index is out of bounds).
2. Handle Special Cases:
○ If index is 0:
■ Call self.pop_first() to remove the first node and return its
result.
○ If index is self.length - 1:
■ Call self.pop() to remove the last node and return its result.
3. Remove Node from Middle:
○ Use self.get(index - 1) to retrieve the node just before the target
index, and store it in prev.
○ Set temp to prev.next, which is the node to be removed.
○ Set prev.next to temp.next to bypass temp and link prev directly to
the next node after temp.
○ Disconnect temp by setting temp.next to None.
4. Update Length:
○ Decrement self.length by 1 to reflect the removal.
5. Return Removed Node's Value:
○ Return temp.value, the value of the removed node.
def remove(self,index):

if index<0 or index >=self.length:

return None

if index==0:

return self.pop_first()

if index==self.length-1:

return self.pop()

prev=self.get(index-1)

temp=prev.next

prev.next=temp.next

temp.next=None

self.length-=1

return temp

You might also like