Question

In: Computer Science

How do you write an append function for a linked list that is a that has...

How do you write an append function for a linked list that is a that has a O(1) Big O notation in Python? The one given in class is O(n). He recommended using a variable to track the end the list. This is the code I have written so far. I don't think I'm properly defining the tail in the add possibly

class Node:

    def __init__(self, init_data):
        self.data = init_data
        self.next = None

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next

    def set_data(self, new_data):
        self.data = new_data

    def set_next(self, new_next):
        self.next = new_next

class UnorderedList:

    def __init__(self):
        self.head = None
        self.tail = None


    def is_empty(self):
        return self.head == None

    def add(self, item):
        temp = Node(item)
        temp.set_next(self.head)
        if self.size()>1:
            self.tail = self.head
            self.head = temp
        else:
            self.head = temp

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.get_next()
        return count

    def search(self, item):
        current = self.head
        found = False
        while current != None and not found:
            if current.get_data() == item:
                found = True
            else:
                current = current.get_next()
        return found

    def remove(self,item):
        current = self.head
        previous = None
        found = False
        while current != None and not found:
            if current.get_data() == item:
                found = True
            else:
                previous = current
                current = current.get_next()
        if found and previous != None:
            previous.set_next(current.get_next())
        elif found and previous is None:
            self.head = None
        else:
            print("The item is not in list")
        return found



    def append(self, data):
        last = self.tail
        print(last2)
        temp = Node(data)
        last.set_next(temp)
        tail = temp
myList = UnorderedList()
myList.add(31)
myList.add(99)
print(myList.size())
myList.add(45)
myList.add(80)
print(myList.size())
myList.append((100))
print(myList.size())

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

#code

class Node:

    def __init__(self, init_data):
        self.data = init_data
        self.next = None

    def
get_data(self):
        return self.data

    def get_next(self):
        return self.next

    def set_data(self, new_data):
        self.data = new_data

    def set_next(self, new_next):
        self.next = new_next

class UnorderedList:

    def __init__(self):
        self.head = None
       
self.tail = None


    def
is_empty(self):
        return self.head == None

   
#adds an element at the beginning
   
def add(self, item):
        temp = Node(item)
        #if list is empty, adding temp as both head and tail
       
if self.head==None:
            self.head = temp
            self.tail= temp
        else:
            #or adding before head node, and updating head node
           
temp.set_next(self.head)
            self.head = temp

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.get_next()
        return count

    def search(self, item):
        current = self.head
        found = False
        while
current != None and not found:
            if current.get_data() == item:
                found = True
            else
:
              current = current.get_next()
        return found

    def remove(self,item):
        current = self.head
        previous = None
       
found = False
        while
current != None and not found:
            if current.get_data() == item:
              found = True
            else
:
                previous = current
                current = current.get_next()
        if found and previous != None:
            previous.set_next(current.get_next())
            #if current.get_next() is None, updating tail node to be previous
           
if current.get_next()==None:
                self.tail=previous
        elif found and previous is None:
            self.head = self.head.get_next()
            #if head node became None, setting tail to None
           
if self.head==None:
                self.tail=None
        else
:
            print("The item is not in list")
        return found


    #adds an element at the end
   
def append(self, data):
        #creating a Node
       
node=Node(data)
        #if self.head is None (list is empty), adding node as both head and tail
       
if self.head==None:
            self.head=node
            self.tail=node
        else:
            #appending after tail
           
self.tail.set_next(node)
            #updating tail
           
self.tail=self.tail.get_next()

    #a helper method to print the list elements for testing
   
def print_list(self):
        node=self.head
        while node!=None:
            print(node.get_data(),end=' ')
            node=node.get_next()
        print()

myList = UnorderedList()
myList.add(31)
myList.add(99)
print(myList.size())
myList.add(45)
myList.add(80)
print(myList.size())
myList.print_list() #80 45 99 31
myList.append((100))
print(myList.size())
myList.print_list() #80 45 99 31 100

#output

2

4

80 45 99 31

5

80 45 99 31 100


Related Solutions

how do you write a bubble sort function in python that sorts a linked list and...
how do you write a bubble sort function in python that sorts a linked list and if any duplicate are placed bext ti each other?
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...
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>...
In C++, Write a function to reverse the nodes in a linked list. You should not...
In C++, Write a function to reverse the nodes in a linked list. You should not create new nodes when you reverse the the linked list. The function prototype:          void reverse(Node*& head); Use the following Node definition: struct Node {    int data;    Node *next; }
Given a doubly linked list in c++, how do I create a function that returns the...
Given a doubly linked list in c++, how do I create a function that returns the pointer to first node in the given pattern, For example, given mainList (a -> b -> c -> d) and sublist  (b -> c), our function should return a Node pointer that points to first node of the sublist in the mainList. If the pattern doesn't exist in the mainList, we should return a nullptr, there are multiple of the same sublist in the mainList,...
Given a doubly linked list in c++, how do I create a function that returns the...
Given a doubly linked list in c++, how do I create a function that returns the pointer to first node in the given pattern, For example, given mainList (a -> b -> c -> d) and sublist  (b -> c), our function should return a Node pointer that points to first node of the sublist in the mainList. If the pattern doesn't exist in the mainList, we should return a nullptr, there are multiple of the same sublist in the mainList,...
how do you add two matrices linked list in java? (am using linked list because 2D...
how do you add two matrices linked list in java? (am using linked list because 2D arrays are not allowed.) ex [1st matrix] 1 3 2 4 2 1 3 2 4 + [2nd matrix] 3 2 3 2 1 4 5 2 3 = [3rd matrix] 4 5 5 6 3 5 8 4 7
C++: Write a reverse function that receives a reference to a integer linked list and reverses...
C++: Write a reverse function that receives a reference to a integer linked list and reverses the order of all the elements in it. For example, if the input linked list is 1 -> 4-> 2-> 3-> 6-> 5}, after processing by this function, the linked list should become 5-> 6-> 3-> 2-> 4-> 1. You need to write a main file to insert elements into the linked list and call the reverseLinkedList() function which takes the reference of first...
Write a function that takes a binary search tree as input and produces a linked list...
Write a function that takes a binary search tree as input and produces a linked list of the entries, with the entries sorted (smallest entries at the front of the list and largest entries at the back). *Hint: use in-order traversal.* C++ there is no any structure
How do you implement stack by using linked list? No code just explain it.
How do you implement stack by using linked list? No code just explain it.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT