Question

In: Computer Science

class SLinkedList: """Singly linked list with access to front and end, and with stored size. """...

class SLinkedList:
"""Singly linked list with access to front and end, and with stored size.
"""

#-------------------------- nested _Node class --------------------------
class _Node:
__slots__ = '_element', '_next' # streamline memory usage

def __init__(self, element, next):
self._element = element
self._next = next

#------------------------------- queue methods -------------------------------
def __init__(self):
"""Create an empty list."""
self._head = None
self._tail = None
self._size = 0

def __len__(self):
"""Return the number of elements in the list."""
return self._size

def isEmpty(self):
"""Return True if the list is empty."""
return self._size == 0
  
# READ THIS!
def __repr__(self):
plist = []
current = self._head
# This is how to traverse a list:
while current != None: # use a while-loop.
plist.append(current._element) # process the stored element.
current = current._next # jump to the next node.
return "SLinkedList(%s)" % repr(plist)

def first(self):
"""Return but do not remove the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
return self._head._element
  
def deleteFirst(self):
"""Remove and return the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.isEmpty(): # special case when list is empty
self._tail = None # removed head had been the tail
return answer
  
def addFirst(self, e):
"""Add element e to the front of the list."""
self._head = self._Node(e, self._head) # create and link a new node
if self._tail == None: # special case when list was empty
self._tail = self._head # added head is the tail
self._size += 1
  
def addLast(self, e):
"""Add e to the end of the list."""
newest = self._Node(e, None) # node will be new tail node
if self.isEmpty():
self._head = newest # special case: previously empty
else:
self._tail._next = newest
self._tail = newest # update reference to tail node
self._size += 1
  
def last(self):
"""Return but do not remove the last element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
return self._tail._element
  
def _nodeAtIndex(self, index):
"""Returns the reference to the node at the given index;
If index is out of range, raise IndexError
"""
# PROBLEM 2
# You can assume that index is non-negative.
# You need to traverse the list and stop at the required index.
# YOUR CODE HERE
raise NotImplementedError()
  
def __getitem__(self, index):
aNode = self._nodeAtIndex(index)
return aNode._element
  
def __setitem__(self, index, value):
# PROBLEM 3
# YOUR CODE HERE
raise NotImplementedError()
  
def deleteLast(self):
"""Remove and return the last element. Runs in O(n) time.
Raise EmptyError if the list is empty.
"""
# PROBLEM 4
# Your code should handle three cases:
# a list of size 0, size 1 and size >=2.
# If the list is of size >= 2
# you need to traverse the list and stop at the second last node;
# that node contains a reference to the last node;
# this reference needs to be copied/assigned to self._tail
# YOUR CODE HERE
  

Solutions

Expert Solution

Complete code

# coding=utf-8
import pytest

class SLinkedList:
"""Singly linked list with access to front and end, and with stored size."""

#-------------------------- nested _Node class --------------------------
class _Node:
__slots__ = '_element', '_next' # streamline memory usage

def __init__(self, element, next):
self._element = element
self._next = next

#------------------------------- queue methods -------------------------------
def __init__(self):
"""Create an empty list."""
self._head = None
self._tail = None
self._size = 0

def __len__(self):
"""Return the number of elements in the list."""
return self._size

def isEmpty(self):
"""Return True if the list is empty."""
return self._size == 0

# READ THIS!
def __repr__(self):
plist = []
current = self._head
# This is how to traverse a list:
while current != None: # use a while-loop.
plist.append(current._element) # process the stored element.
current = current._next # jump to the next node.
return "SLinkedList(%s)" % repr(plist)

def first(self):
"""Return but do not remove the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
return self._head._element

def deleteFirst(self):
"""Remove and return the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.isEmpty(): # special case when list is empty
self._tail = None # removed head had been the tail
return answer

def addFirst(self, e):
"""Add element e to the front of the list."""
self._head = self._Node(e, self._head) # create and link a new node
if self._tail == None: # special case when list was empty
self._tail = self._head # added head is the tail
self._size += 1

def addLast(self, e):
"""Add e to the end of the list."""
newest = self._Node(e, None) # node will be new tail node
if self.isEmpty():
self._head = newest # special case: previously empty
else:
self._tail._next = newest
self._tail = newest # update reference to tail node
self._size += 1

def last(self):
"""Return but do not remove the last element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
return self._tail._element

def _nodeAtIndex(self, index):
"""Returns the reference to the node at the given index;
If index is out of range, raise IndexError
"""

if(self.isEmpty() or index>=self._size):
raise IndexError("Index out of range")
temp=self._head
i=0
while i!=index:
temp=temp._next
i+=1
return temp

def __getitem__(self, index):
aNode = self._nodeAtIndex(index)
return aNode._element

def __setitem__(self, index, value):
if(index>self._size):
raise IndexError("Index out of range")
if index==0:
self.addFirst(value)
return
temp=self._head._next
i=1
while i!=index:
temp=temp._next
i+=1
temp._element=value


def deleteLast(self):
"""Remove and return the last element. Runs in O(n) time.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
self._size -= 1
if self._head.next==None:
value=self._head._element
self._head=self._tail=None
return value
temp=self._head
while temp._next._next!=None:
temp=temp._next
value=temp._next._element
tail=temp
tail._next=None
return value

Code snaps for indent

If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.


Related Solutions

A circular doubly-linked list .(a) In a circular doubly-linked list, there is no front or end;...
A circular doubly-linked list .(a) In a circular doubly-linked list, there is no front or end; the nodes form a full circle. Instead of keeping track of the node at the front, we keep track of a current node instead. Write a class for a circular doubly-linked list using the attached Job class as your node objects. It should have: • A private instance variable for the current node • A getCurrent() method that returns a reference to the current...
Using the singly linked list code as a base, create a class that implements a doubly...
Using the singly linked list code as a base, create a class that implements a doubly linked list. A doubly linked list has a Previous link so you can move backwards in the list. Be sure the class is a template class so the user can create a list with any data type. Be sure to test all the member functions in your test program. c++
1. Considering singly linked list, be able to determine if inserting nodes at the end of...
1. Considering singly linked list, be able to determine if inserting nodes at the end of a LinkedList is less time-efficient than inserting them at the front of the list. 2. Be able to differentiate between the data structures Stack, Queue, and Linked List. 3. Determine between the acronyms LIFO and FIFO, and be able to give one real life example where each is applicable
Q1) In the implementation of Singly linked list we had an integer variable called size that...
Q1) In the implementation of Singly linked list we had an integer variable called size that keeps track of how many elements in the list. Also, we have a reference “tail” that points to the last node in the list. You are asked to re-implement the concept of singly linked list without using variable size, and without using reference “tail”. a) What are the methods of the main operation of singly linked list that need to be changed? Rewrite them...
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;...
Objectives: Define the new class type: Queue using a singly linked list. Define the new class...
Objectives: Define the new class type: Queue using a singly linked list. Define the new class type: Jukebox which creates three objects of type Queue class. Practice enqueue-ing and dequeue-ing elements from the top of your singly linked list Queue class. Test the implementation of the class: MyTunes. The class files are here: https://drive.google.com/file/d/1yCCQeZCS-uLoL_CK0Et9dX-KCaokXQxR/view?usp=sharing class MyTunes Creates an object of type MyTunes class that partially simulate the digital jukebox TouchTunes, using a queue which holds playlist. Tests the implementation of...
I've provided a Node class that implements a node of a simple singly-linked list (with .value...
I've provided a Node class that implements a node of a simple singly-linked list (with .value and .next fields), and an empty LinkedList class. Your task is to implement LinkedList.sort(l), where given the node l as the head of a singly-linked list, LinkedList.sort(l) sorts the nodes in the list into ascending order according to the values in the .value field of each node. Your implementation should do an in-place update of the list. It is ok to use a simple...
Write a template class that implements an extended queue (use singly Linked List) in c++ please...
Write a template class that implements an extended queue (use singly Linked List) in c++ please create 3 classes please create 3 classes please create 3 classes please create 3 classes please create 3 classes Ex: ExtendedQueue int_queue; ExtendedQueue double_queue; ExtendedQueue char_queue; –Write a program to test this template class. you have to use inheritance so you will create 3 classes : so you will create 3 classes : so you will create 3 classes : so you will create...
In C++, Implement the queue ADT with a singly linked list
In C++, Implement the queue ADT with a singly linked list
Exercise 1: Write a program in Java to manipulate a Singly Linked List: 1. Create Singly...
Exercise 1: Write a program in Java to manipulate a Singly Linked List: 1. Create Singly Linked List 2. Display the list 3. Count the number of nodes 4. Insert a new node at the beginning of a Singly Linked List. 5. Insert a new node at the end of a Singly Linked List 6. Insert a new node after the value 5 of Singly Linked List 7. Delete the node with value 6. 8. Search an existing element in...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT