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

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
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.
how to do circular linked list in c++ (inset and delet and display)
how to do circular linked list in c++ (inset and delet and display)
write a few English sentences describing how you would change the Linked-Chain implementation of the List...
write a few English sentences describing how you would change the Linked-Chain implementation of the List ADT to support removal of a node from the middle retaining order. Write PSEUDOCODE to insert a node at position 2 in a doubly-linked list (assume position follows classic indexing from 0 to item_count - 1)
Task 1: [10 Marks] Write a function “reverse” in your queue class (linked list implementation) that...
Task 1: [10 Marks] Write a function “reverse” in your queue class (linked list implementation) that reverses the whole queue. In your driver file (main.cpp), create an integer queue, push some values in it, call the reverse function to reverse the queue and then print the queue.
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. In paragraph 1 Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. In pragraph 2 Replace "We" with v"i" This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would...
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. Replace "sh" with ph This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would not do that Paragraph 2 We...
In this problem, you will write a program that reverses a linked list. Your program should...
In this problem, you will write a program that reverses a linked list. Your program should take as input a space-separated list of integers representing the original list, and output a space-separated list of integers representing the reversed list. Your algorithm must have a worst-case run- time in O(n) and a worst-case space complexity of O(1) beyond the input. For example, if our input is: 5 7 1 2 3 then we should print: 3 2 1 7 5 Please...
# List at least three functions in the linked list toolbox, including function names and their...
# List at least three functions in the linked list toolbox, including function names and their functionality. # Assuming we have already implemented all functions in the linked list toolbox and we have a pointer head_ptr pointing to the front of a linked list. Write a few lines to insert the number 42 and make it the second item in the list. Note: if the list was originally empty, then it should be the first in the list.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT