Question

In: Computer Science

In python: implement a singly linked list with following functions: - add_head(e) - add_tail(e) - find_3rd_to_last()...

In python:

implement a singly linked list with following functions:

- add_head(e)

- add_tail(e)

- find_3rd_to_last() - returns element located at third-to-last in the list

- reverse() - reveres the linked list, note, this is not just printing elements in reverse order, this is actually reversing the list

Solutions

Expert Solution

Program :

Implementation of a single linked list in python.

see the program screenshot for proper indentation.

main.py

#Node class with data and link part of a node in the linked list
class Node :
    def __init__(self, data) :
        self.data = data
        self.link = None
      
      
#linked list class containing a head of the linked list
class LinkedList :
    def __init__(self) :
        self.head = None  #stating node
    
    #display method for the linked list
    def display(self) :
        if self.head is None:
            print("List is empty")
            return
        else:
            print("\n[",end="")
            cur = self.head    #cur - current node
            while cur is not None:
                print(cur.data , end=" ")
                cur = cur.link
                
            print("]\n",end="")
         
    #add_head : add element at the head or staring of the linked list        
    def add_head(self,e) :
        new_node = Node(e)  #creating a new node
        new_node.link = self.head  #setting new_node link to head
        self.head = new_node  #changing head to new node
    
    #add_tail : add element at the end of the linked list
    def add_tail(self,e) :
        new_node = Node(e)  #new node
        #if head is None i.e. list is empty then change head to new node and return
        if self.head is None:
            self.head = new_node
            return
        #otherwise traverse the list upto the last element
        cur = self.head
        while(cur.link is not None) :
            cur = cur.link
        
        #then add the new node in the link of the last element in the linked list
        cur.link = new_node
      
      
    #find_3rd_to_last  : finds the 3rd element from the last of the linked list   
    def find_3rd_to_last(self) :
        #if list size is less than 3 then return None
        if self.head is None or self.head.link is None or self.head.link.link is None :
            return None
        
        #otherwise point to the first and the 3rd element in the list
        pointerA = self.head; #first element
        pointerB = self.head.link.link #third element from the starting
        
        #traverse till pointerB reaches the end of the list 
        #then pointerA  will be pointing to the 3rd last element in the list
        while(pointerB.link is not None) :
            pointerA = pointerA.link
            pointerB = pointerB.link
        
        return pointerA
    
    #reverse : actual reverse of the liked list
    def reverse(self) :
        #if array size is <= 1 then return the head
        if self.head is None or self.head.link is None :
            return self.head
        
        #otherwise take three nodes prvious, current, next
        prev_node = self.head
        cur_node = prev_node.link
        next_node = cur_node.link
        self.head.link = None  #make the head point to None at starting
        
        while(cur_node is not None ) :
            cur_node.link = prev_node   #current.link = previous
            prev_node = cur_node        #previous = current
            cur_node = next_node        #current = next
            if next_node is not None :  #next = next.link
                next_node = next_node.link
        
        #  head->1->2->3->4->5->None
        #  None<-1<-2<-3<-4<-5<-head
        self.head = prev_node  #previous will be having the last node at the end so head will be replaced by the previous
        
        
#main program    
#using this linked list in the program
linked_list = LinkedList()
linked_list.add_head(2)
linked_list.add_tail(3)
linked_list.add_tail(10)
linked_list.add_head(1)
linked_list.add_tail(20)
linked_list.add_tail(30)

print("Dispalying the created list")
linked_list.display()

#taking the 3rd element from the last in node
node = linked_list.find_3rd_to_last()
print("3rd to last element : ",node.data)  #print third element from the last
    
#applying the reverse method on the list
linked_list.reverse()
#displaying the list after reversing iter
print("After reverse  : ")
linked_list.display()


    

Output :

Program screenshots :


Related Solutions

In C++, Implement the queue ADT with a singly linked list
In C++, Implement the queue ADT with a singly linked list
Design, Develop and Implement the following operations on Singly Linked List (SLL) with a single field...
Design, Develop and Implement the following operations on Singly Linked List (SLL) with a single field data a.   Create a SLL for N Data by using front insertion. b.   Display the status of SLL and count the number of nodes in it c.   Perform Insertion and Deletion at End of SLL d.   Perform Insertion at the third position. e.    Delete the element at the Front of SLL f.     Perform Deletion at second position of SLL g.     Display the content. Design,...
PYTHON: Describe a recursive algorithm that counts the number of nodes in a singly linked list.
PYTHON: Describe a recursive algorithm that counts the number of nodes in a singly linked list.
8. Assume you have a singly linked list with no tail pointer. Implement removeTail(). Raise an...
8. Assume you have a singly linked list with no tail pointer. Implement removeTail(). Raise an exception of the method is called on an empty list. template<typename Object> class LinkedList { private: class Node { Object data; Node* next; }; Node *head; public: LinkedList() : head(nullptr) {} Object removeTail(Object data); }; 9. What are iterators? What purpose do they serve? 10. What does it mean to invalidate an iterator? 11. Explain the difference between separate chaining and open addressing in...
I was supposed to conver a singly linked list to a doubly linked list and everytime...
I was supposed to conver a singly linked list to a doubly linked list and everytime I run my program the output prints a bunch of random numbers constantly until I close the console. Here is the code. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> struct node { int data; struct node *next; struct node *prev; }; //this always points to first link struct node *head = NULL; //this always points to last link struct node *tail = NULL;...
You are given a singly linked list. Write a function to find if the linked list...
You are given a singly linked list. Write a function to find if the linked list contains a cycle or not. A linked list may contain a cycle anywhere. A cycle means that some nodes are connected in the linked list. It doesn't necessarily mean that all nodes in the linked list have to be connected in a cycle starting and ending at the head. You may want to examine Floyd's Cycle Detection algorithm. /*This function returns true if given...
C++ coding functions Implement the following class using linked lists. Creating a simple linked list class...
C++ coding functions Implement the following class using linked lists. Creating a simple linked list class to use is probably your first step.(Please do not use collections like .push() . pop(), etc.) and instead create the implementation A templated stack class that stores type T with the following public functions: - void Push(T t) - adds t to the top of the stack - T Pop() - asserts that the stack is not empty then removes and returns the item...
Write a program to implement linked list data structure that will have following functions: a. Append...
Write a program to implement linked list data structure that will have following functions: a. Append a node in the list b. Insert a node in the list c. Delete a node from the list d. Display list e. Find maximum value in the list f. Find how many times a value exists in the list. g. Search Portion of the code is give below. You have to write code for the items (e, f, g) Program: #include<stdlib.h> #include<stdio.h> #include<iostream>...
Problem Description: Using Python write a Singly‐Linked List (with only the Head pointer) that supports the...
Problem Description: Using Python write a Singly‐Linked List (with only the Head pointer) that supports the following operations: 1. Adding an element at the middle of the list. 2. Removing the middle element of the list (and return the data). 3. Adding an element at a given index. 4. Removing an element at a given index (and return the data). For #1 and #2, ignore the operations if the length of the list is an even number. For #3, if...
In Python, I've created a Node class for implementing a singly linked list. My Code: class...
In Python, I've created a Node class for implementing a singly linked list. My Code: class Node: def __init__(self,initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data = newdata def setNext(self,newnext): self.next = newnext class SinglyLinkedList: def __init__(self): self.head = None def add(self,key): addkey = Node(key) addkey.setNext(self.head) self.head = addkey Now the question is: Create an append method that is O(1) by modifying the constructor of the SinglyLinkedList class by adding...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT