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

Doubly_LinkedList

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Doubly_LinkedList

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

DoublyLinkedList: Constructor

Design and implement a Python program that defines two classes: Node and
DoublyLinkedList.

1. Create a class called Node, which will represent a single node in a


doubly-linked list. The class should have the following attributes:
a. value: The data contained in the node.
b. next: A reference to the next node in the list.
c. prev: A reference to the previous node in the list.
2. Create a class called DoublyLinkedList, which will represent a
doubly-linked list. The class should have the following attributes:
a. head: A reference to the head (first) node of the list.
b. tail: A reference to the tail (last) node of the list.
c. length: An integer representing the number of nodes in the list.

When initializing a new instance of the DoublyLinkedList class, the user should
provide a value for the first node.

The constructor should create a new instance of the Node class using the
provided value and assign it as both the head and tail of the list.

The length attribute should be initialized to 1, as the list contains one node at the
beginning.
Algorithm

1. Define the Node Class:

● Create a class named Node with an __init__ method.


● The __init__ method should accept a parameter value.
● Inside the method:
○ Set self.value to value (this holds the data for the node).
○ Initialize self.next to None (this will point to the next node).
○ Initialize self.prev to None (this will point to the previous node).

2. Define the DoublyLinkedList Class:

● Create a class named DoublyLinkedList with an __init__ method.


● The __init__ method should accept a parameter value.
● Inside the method:
○ Create a new instance of Node with value and assign it to
new_node.
○ Set self.head to new_node (since this is the only node, it will be
both the head and tail).
○ Set self.tail to new_node.
○ Initialize self.length to 1, as the list currently has one node.
# class Node:

class Node:

def __init__(self,value):

self.value=value

self.next=None

self.prev=None

# class DoublyLinkedList:

class DoublyLinkedList:

def __init__(self,value):

new_node=Node(value)

self.head=new_node

self.tail=new_node

self.length=1

my_doubly_linked_list = DoublyLinkedList(7)

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

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

print('Length:', my_doubly_linked_list.length)
DoublyLinkedLlist: Print the List
Extend the previously implemented DoublyLinkedList class by adding a
print_list method that prints all the values of the nodes in the list from head to tail.

The method should perform the following tasks:

1. Start with the head of the list.


2. Traverse the list:
○ Use a temporary pointer to iterate through each node.
○ Print the value of each node.
3. Stop when the end of the list is reached (i.e., when the current node's next is
None).
4. Ensure the list is printed in order, starting from the first node to the last.

# Method to print all nodes in the list

def print_list(self):

temp = self.head

while temp is not None:

print(temp.value)

temp = temp.next
DoublyLinkedList: Append

Extend the previously implemented DoublyLinkedList class by adding an append


method that inserts a new node with a given value at the end of the list.

The method should perform the following tasks:

1. Create a new instance of the Node class with the provided value.
2. If the list is empty (i.e., the head is None), set the head and tail of the list to the
newly created node.
3. If the list is not empty, perform the following steps:
a. Set the next attribute of the current tail node to the new node.
b. Set the prev attribute of the new node to the current tail node.
c. Update the tail of the list to the new node.
4. Increment the length attribute of the list by 1.
5. Return True to indicate that the operation was successful.
Algorithm for append Method

1. Create a New Node:


○ Create a new node with the given value by initializing it with the Node
class.
2. Check if List is Empty:
○ If self.head is None (i.e., the list is empty):
■ Set both self.head and self.tail to the new node, as it is the
only node in the list.
3. If List is Not Empty:
○ Set self.tail.next to the new node, linking the current tail to the new
node.
○ Set new_node.prev to self.tail, linking the new node back to the
current tail.
○ Update self.tail to the new node, making it the new last node in the
list.
4. Update Length:
○ Increment self.length by 1 to reflect the addition of the new node.
5. Return Success:
○ Return True to indicate that the node was successfully added to the list.
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

new_node.prev=self.tail

self.tail=new_node

self.length+=1

return True
DoublyLinkedList: Pop

Further extend the DoublyLinkedList class by adding a pop method that removes the
last node from the list and returns it.

The method should perform the following tasks:

1. If the list is empty (i.e., the length is 0), return None.


2. Store a reference to the current tail node in a temporary variable.
3. If the list has only one node (i.e., the length is 1), set both the head and tail of the
list to None.
4. If the list has more than one node, perform the following steps:
a. Update the tail of the list to be the previous node of the current tail.
b. Set the next attribute of the new tail node to None.
c. Set the prev attribute of the removed node (stored in the temporary
variable) to None.
5. Decrement the length attribute of the list by 1.
6. Return the removed node (stored in the temporary variable).
Algorithm for pop Method

1. Check if List is Empty:


○ If self.length is 0 (the list is empty), return None because there is no
node to pop.
2. Store the Tail Node:
○ Set temp to self.tail to hold the reference to the last node.
3. Update Tail:
○ Set self.tail to self.tail.prev, making the previous node the new
tail of the list.
○ Set self.tail.next to None to disconnect the old tail node from the
list.
4. Disconnect Popped Node:
○ Set temp.prev to None to fully detach the popped node from the list.
5. Check if List is Empty After Popping:
○ If self.length is now 0 (i.e., the list had only one node):
■ Set both self.head and self.tail to None, making the list
empty.
6. Decrement Length:
○ Decrement self.length by 1 to reflect the removal of the node.
7. Return Popped Node:
○ Return temp, which contains the reference to the popped node.
def pop(self):

if self.length==0:

return None

temp=self.tail

self.tail=self.tail.prev

self.tail.next=None

temp.prev=None

if self.length==0:

self.head=None

self.tail=None

self.length-=1

return temp
DLL: Prepend

Implement the prepend method that inserts a new node with a given
value at the beginning of the list.

The method should perform the following tasks:

1. Create a new instance of the Node class with the provided value.
2. If the list is empty (i.e., the length is 0), set the head and tail of
the list to the newly created node.
3. If the list is not empty, perform the following steps:
a. Set the next attribute of the new node to the current head
node.
b. Set the prev attribute of the current head node to the new
node.
c. Update the head of the list to the new node.
4. Increment the length attribute of the list by 1.
5. Return True to indicate that the operation was successful.
Algorithm: Prepend Method in Doubly Linked List

Objective: Insert a new node with a given value at the beginning of the list.

Input:

● value: The value to be added at the beginning of the list.

Output:

● Returns True after successfully adding the node.

Steps:

1. Create New Node:


○ Initialize a new node (new_node) with the given value.
2. Check if List is Empty:
○ If the list's length is 0 (meaning the list is empty):
■ Set both the head and tail pointers of the list to new_node,
making the new node the only node in the list.
3. If List is Not Empty:
○ Set the next pointer of new_node to point to the current head of the list.
○ Set the prev pointer of the current head to point back to new_node.
○ Update the head pointer of the list to point to new_node, making it the
new first node.
4. Update List Length:
○ Increment the length of the list by 1.
5. Return Success:
○ Return True to indicate the operation completed successfully.
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.prev=new_node

self.head=new_node

self.length+=1

return True
DLL: Pop First

Implement the pop_first method that removes the first node from the list
and returns it.

The method should perform the following tasks:

1. If the list is empty (i.e., the length is 0), return None.


2. Store a reference to the current head node in a temporary variable.
3. If the list has only one node (i.e., the length is 1), set both the head
and tail of the list to None.
4. If the list has more than one node, perform the following steps:
a. Update the head of the list to be the next node of the current
head.
b. Set the prev attribute of the new head node to None.

c. Set the next attribute of the removed node (stored in the

temporary variable) to None.


5. Decrement the length attribute of the list by 1.

6. Return the removed node (stored in the temporary variable).


Algorithm: Pop First Method in Doubly Linked List

Objective: Remove and return the first node from the list.

Input:

● No input is required for this operation.

Output:

● Returns the value of the removed node if the list is not empty; returns None if the list is
empty.

Steps:

1. Check if List is Empty:


○ If the list's length is 0 (meaning the list is empty), return None immediately, as
there is no node to remove.
2. Store the Current Head:
○ Assign the current head node to a temporary variable temp. This allows us to
keep a reference to the node we will be removing.
3. Check if List Has Only One Node:
○ If the list's length is 1 (meaning there is only one node):
Set both head and tail pointers of the list to None, making the list

empty.
4. If List Has More Than One Node:
○ Update the head pointer to the second node (i.e., self.head.next).
Set the prev pointer of the new head node to None, detaching the old head from

the list.
○ Set the next pointer of temp (the old head) to None, fully detaching it from the
list.
5. Update List Length:
○ Decrement the list's length by 1.
6. Return the Value of the Removed Node:
○ Return the value of temp (the removed node).
def pop_first(self):
if self.length==0:
return None
temp=self.head
if self.length==1:
self.head=None
self.tail=None
else:
self.head=self.head.next
self.head.prev=None
temp.next=None
self.length-=1
return temp
DLL: Get
Implement the get method for the DoublyLinkedList class that
retrieves a node at a specific index in the list.

The method should perform the following tasks:

1. If the given index is out of bounds (i.e., it is less than 0 or


greater than or equal to the list length), return None.
2. Initialize a temporary variable, temp, to point to the head of
the list.
3. If the index is less than half of the list length, iterate through
the list from the head, updating the temp variable until the
desired index is reached.
4. If the index is greater than or equal to half of the list length,
start iterating from the tail of the list, updating the temp
variable until the desired index is reached.
5. Return the node at the desired index (i.e., the temp variable).
Algorithm: Get Method in Doubly Linked List

Objective: Retrieve the node at a specific index in the doubly linked list.

Input:

● index: The target index of the node to retrieve.

Output:

● Returns the node at the given index if it exists; otherwise, returns None.

Steps:

1. Check if Index is Out of Bounds:


○ If index is less than 0 or greater than or equal to the length of the list
(self.length), return None immediately because the index is invalid.
2. Determine the Starting Point for Traversal:
○ Initialize a variable temp:
■ If index is less than half of the list’s length (self.length / 2), set
temp to self.head and iterate from the beginning of the list.
■ If index is greater than or equal to half of the list’s length, set temp to
self.tail and iterate from the end of the list.
3. Iterate to the Desired Index:
○ If starting from the head, use a loop to move temp to the next node until reaching
the target index.
○ If starting from the tail, use a loop to move temp to the previous node until
reaching the target index.
4. Return the Node at the Desired Index:
○ Return temp, which now points to the node at the desired index.
def get(self, index):
if index < 0 or index >= self.length:
return None
if index < self.length // 2:
temp = self.head
for _ in range(index):
temp = temp.next
else:
temp = self.tail
for _ in range(self.length - 1, index, -1):
temp = temp.prev
return temp
DLL: Set
Implement the set_value method for the DoublyLinkedList class
that updates the value of a node at a specific index in the list.

The method should perform the following tasks:

1. Call the get method with the given index to retrieve the node at
the specified index. Store the result in a temporary variable,
temp.
2. If the temp variable contains a valid node (i.e., it is not None),
update the node's value attribute with the provided value and
return True.
3. If the temp variable does not contain a valid node (i.e., it is
None), return False to indicate that the operation was
unsuccessful.
Algorithm: Set Value Method in Doubly Linked List

Objective: Update the value of the node at a specific index in the list.

Input:

● index: The index of the node whose value needs to be updated.


● value: The new value to assign to the node at the specified index.

Output:

● Returns True if the value was successfully updated.


● Returns False if the operation was unsuccessful (e.g., if the index is out of bounds).

Steps:

1. Retrieve Node at Specified Index:


○ Call the get method with the index to find the node at that position.
○ Store the result in a variable temp.
2. Check if Node Exists:
○ If temp is a valid node (i.e., not None):
■ Update temp.value with the given value.
■ Return True to indicate the value was successfully updated.
3. Return Failure if Node Does Not Exist:
○ If temp is None (indicating that the index is out of bounds):
■ Return False to indicate that the operation was unsuccessful.

def set_value(self, index, value):


temp = self.get(index)
if temp:
temp.value = value
return True
return False
DLL: Insert
Implement the insert method for the DoublyLinkedList class that inserts
a new node with a given value at a specific index in the list.

The method should perform the following tasks:

1. If the given index is out of bounds (i.e., it is less than 0 or greater


than the list length), return False.
2. If the index is 0, call the prepend method with the provided value
and return its result.
3. If the index is equal to the list length, call the append method with
the provided value and return its result.
4. Create a new instance of the Node class with the provided value.
5. Call the get method with the index minus 1 to retrieve the node
before the desired index, and store the result in a variable, before.
6. Set a variable, after, to point to the next node after the before
node.
7. Update the prev and next attributes of the new node to point to the
before and after nodes, respectively.
8. Update the next attribute of the before node and the prev attribute
of the after node to point to the new node.
9. Increment the length attribute of the list by 1.
10. Return True to indicate that the operation was successful.
Algorithm: Insert Method in Doubly Linked List

Objective: Insert a new node with a given value at a specified index in the
list.

Input:

● index: The position in the list where the new node should be
inserted.
● value: The value to be added to the new node.

Output:

● Returns True if the node is successfully inserted.


● Returns False if the index is out of bounds and the operation cannot
be performed.

Steps:

1. Check Index Bounds:


○ If index is less than 0 or greater than self.length, return
False, as the index is invalid.
2. Handle Special Cases:
○ If index is 0, call the prepend method to add the node at the
beginning and return the result of prepend.
○ If index is equal to self.length, call the append method to
add the node at the end and return the result of append.
3. Insert Node in the Middle of the List:
○ Create a new node, new_node, with the given value.
○ Retrieve the node at index - 1 (the node before the insertion
point) using the get method and store it in before.
○ Set after as the node currently following before (i.e.,
before.next).
4. Update Pointers to Insert the New Node:
○ Set new_node.prev to before and new_node.next to after.
○ Update before.next to point to new_node.
○ Update after.prev to point back to new_node.
5. Update List Length:
○ Increment self.length by 1 to reflect the addition of the new
node.
6. Return Success:
○ Return True to indicate that the insertion was successful.

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)

before=self.get(index-1)

after=before.next

new_node.prev=before

new_node.next=after

before.next=new_node

after.prev=new_node

self.length+=1

return True
DLL: Remove
Implement the remove method for the DoublyLinkedList class
that removes a node at a specific index in the list and returns it.

The method should perform the following tasks:

1. If the given index is out of bounds (i.e., it is less than 0 or


greater than or equal to the list length), return None.
2. If the index is 0, call the pop_first method and return its
result.
3. If the index is equal to the list length minus 1, call the pop
method and return its result.
4. Call the get method with the given index to retrieve the
node to be removed, and store the result in a temporary
variable, temp.
5. Update the prev attribute of the temp.next node and the
next attribute of the temp.prev node to remove temp from
the list.
6. Set the next and prev attributes of the temp node to None.
7. Decrement the length attribute of the list by 1.
8. Return the removed node (i.e., the temp variable).

Algorithm: Remove Method in Doubly Linked List


Objective: Remove and return the node at a specified index in the
list.
Input:

● index: The position of the node to be removed.


Output:

● Returns the node at the specified index if the removal is


successful.
● Returns None if the index is out of bounds.
Steps:

1. Check Index Bounds:


○ If index is less than 0 or greater than or equal to
self.length, return None, as the index is invalid.
2. Handle Special Cases:
○ If index is 0, call the pop_first method to remove
and return the first node.
○ If index is self.length - 1, call the pop method
to remove and return the last node.
3. Retrieve the Node at the Given Index:
○ Use the get method to retrieve the node at the
specified index and store it in a temporary variable
temp.
4. Update Pointers to Remove the Node:
○ Set before to temp.prev (the node before temp).
○ Set after to temp.next (the node after temp).
○ Update before.next to point to after, bypassing
temp.
○ Update after.prev to point to before, bypassing
temp.
5. Update List Length:
○ Decrement self.length by 1 to reflect the removal
of the node.
6. Return the Removed Node:
○ Return temp, which is the node that was removed.

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()

temp=self.get(index)

before=temp.prev

after=temp.next

self.length-=1

return temp

You might also like