JSFiddle - React, Tailwind, and code Playground

by Jessie Lau

JavaScript

# Singly Linked List Implementation
# I've gotten the code started for you, showing you what your node class
# should look like


class Node:

    def __init__(self, val):
        # have our node hold a value
        self.value = val
        # initially it will not keep track of a node that comes after
        self.next = None


class SinglyLinkedList:

    def __init__(self):
        # initially set our head attribute to None
        self.head = None
        # self.whole_data_lst = []

    def traverse(self):
        # this method prints the values of of all the nodes in the list
        print("traversing...")
        if self.head is not None:
            # we will initialize our current node as the head node
            current_node = self.head
            # print the value of the head node
            print(current_node.value)
            # this while loop moves us forward through the linked list
            while current_node.next is not None:
                current_node = current_node.next
                print(current_node.value)
        # in the case that there are no nodes
        else:
            print("No nodes")
            return False

# create a method to add a new node
    def add_node(self, val):
        # creating a new node
        new_node = Node(val)
        # self.whole_data_lst.append(new_node.value)
        # if there are no nodes yet set the head attribute to our new node
        if self.head is None:
            self.head = new_node
        # else we will have to traverse to the last node in the chain and
        # add our new node to the end
        else:
            current_node = self.head
            while current_node.next is not None:
                current_node = current_node.next
            current_node.next = new_node


# now implement the following functions
# as you are going through/when you finish each method,
# make comments so you are aware of what's going on in each method
    def print_as_list(self):
        # this...