Beispiel #1
0
def addition(llist1,llist2):
    curr1 = llist1.head
    curr2 = llist2.head
    myList = LinkedList()
    carry = 0 
    temp = None 

    while(curr1 is not None or curr2 is not None):
        lvalue= curr1.data if curr1 else 0
        rvalue= curr2.data if curr2 else 0 

        val = lvalue + rvalue + carry
        carry = 1 if  val >10 else 0
        val = val % 10 

        newNode = Node(val)
        if myList.head is None:
            myList.head = newNode
            temp = myList.head
        else:
            temp.next = newNode
            temp = temp.next  
        
        if curr1 is not None:
            curr1 = curr1.next
        if curr2 is not None:
            curr2 = curr2.next 

    if carry>0:
        temp.next = Node(carry) 
    
    return myList
Beispiel #2
0
 def test_in_filter_preserves_front_and_back_if_needed(self):
     ll = LinkedList()
     item1 = ll.add_to_front(123, 123123)
     item2 = ll.add_to_front(234234, 92834923)
     ll.in_filter(None)
     assert ll.front == item2
     assert ll.back == item1 
Beispiel #3
0
 def test_in_filter_None_equal_to_identity(self):
     ll = LinkedList()
     item1 = ll.add_to_front(123, 8907067)
     ll.in_filter(None)
     assert item1.key == ll.front.key
     assert item1.value == ll.front.value
     assert ll.length == 1
Beispiel #4
0
 def test_prev_from_front_is_none(self):
     '''Item at the front has None as prev pointer'''
     ll = LinkedList()
     ll.add_to_front(0, 98)
     assert ll.front.prev == None
     ll.add_to_front(123, 98)
     assert ll.front.prev == None
Beispiel #5
0
 def test_last_item_point_to_none(self):
     '''Item at the back has None as next pointer'''
     ll = LinkedList()
     ll.add_to_back(0, 23)
     assert ll.back.next == None
     ll.add_to_back(123, 234)
     assert ll.back.next == None
Beispiel #6
0
class AnimalShelter:

    def __init__(self):
        self.dogs = LinkedList()
        self.cats = LinkedList()
        self.counter = 0

    def enqueue(self, animal):
        if animal.species == 'dog':
            self.dogs.add((animal, self.counter))
        elif animal.species == 'cat':
            self.cats.add((animal, self.counter))
        else:
            raise Exception("Unsupported animal type.")
        self.counter += 1

    def dequeue_dog(self):
        return self.dogs.pop()

    def dequeue_cat(self):
        return self.cat.pop()

    def dequeue_any(self):
        dog = self.dogs.head
        cat = self.cats.head
        if dog is None:
            return cat
        if cat is None:
            return dog

        if dog.value[1] > cat.value[1]:
            return cat
        else:
            return dog
def test_insert_two():
    l_list = LinkedList()
    l_list.insert("David")
    l_list.insert("Thomas")
    assert l_list.head.get_data() == "Thomas"
    head_next = l_list.head.get_next()
    assert head_next.get_data() == "David"
Beispiel #8
0
def reverse_in_place(ll):
    """
    Steps:
             a -> b -> c
          <- a    b -> c  * When we are changing b we need references to a and c
          <- a <- b    c
          <- a <- b <- c
    """
    if ll.length < 2:
        return ll

    previous = ll.head
    current = previous.next
    later = current.next
    previous.next = None

    while True:
        current.next = previous
        previous = current
        current = later
        if current is not None:
            later = current.next
        else:
            break

    reverse_list = LinkedList()
    reverse_list.head = previous
    return reverse_list
Beispiel #9
0
 def create_random_list(self):
     random_list = LinkedList()
     x = random.randint(1, 200)
     for i in range(0, x):
         value = random.randint(1, 10000)
         random_list.append(value)
     return random_list
 def test_reverse_single(self):
     ll = LinkedList(358)
     self.assertEqual(358, ll.peek())
     self.assertEqual(1, len(ll))
     ll.reverse()
     self.assertEqual(358, ll.peek())
     self.assertEqual(1, len(ll))
Beispiel #11
0
 def test_insert_after(self):
     llist = LinkedList()
     for i in xrange(10):
         llist.push_back(i)
     for item in llist:
         if item.value % 2 == 0:
             llist.insert_after(item, item.value - 1)
     self.assertEqual([0,-1,1,2,1,3,4,3,5,6,5,7,8,7,9], [node.value for node in llist])
Beispiel #12
0
 def test_add_back_multiple_equal_items(self):
     '''Adding the same item to the back of the list multiple times creates
     different linked list objects with the same item'''
     ll = LinkedList()
     ll.add_to_back(12)
     ll.add_to_back(12)
     assert ll.back.key == ll.back.prev.key 
     assert ll.back != ll.back.prev 
Beispiel #13
0
def main():
    test = LinkedList()
    for i in range(20):
        test.add(i)
    print(test)
    print('Find the node before last', findKelementh(test, 2))
    print('Find the last node', findKelementh(test, 1))
    print('Finding 12th to last Node: ', findKelementh(test, 12))
Beispiel #14
0
 def test_remove_updates_head_if_necessary(self):
     '''Removing head, updates head''' 
     ll = LinkedList()
     item1 = ll.add_to_front(1234)
     item2 = ll.add_to_front(list())
     assert ll.front == item2
     ll.remove(item2)
     assert ll.front == item1
Beispiel #15
0
 def test_removed_item_has_no_parent(self):
     '''Removing an item also removes any references from the item to the 
     list'''
     ll = LinkedList()
     litem = ll.add_to_back(list())
     assert litem.parent()
     ll.remove(litem)
     assert litem.parent == None
Beispiel #16
0
 def test_remove_all_items_deletes_front_and_back(self):
     ll = LinkedList()
     item1 = ll.add_to_back("lkjh")
     item2 = ll.add_to_back([1,2,3])
     ll.remove(item2)
     ll.remove(item1)
     assert ll.front == None
     assert ll.back == None
Beispiel #17
0
 def test_remove_updates_back_if_necessary(self):
     '''Removing back updates back'''
     ll = LinkedList()
     item1 = ll.add_to_back(123)
     item2 = ll.add_to_back("lkj")
     assert ll.back == item2
     ll.remove(item2)
     assert ll.back == item1
Beispiel #18
0
 def test_map_filter_equal_to_identity(self):
     ll = LinkedList()
     item1 = ll.add_to_front(123, 8907067)
     ll2 = ll.filter(None)
     item2 = ll2.front
     assert item1.key == item2.key
     assert item1.value == item2.value
     assert ll.length == ll2.length
Beispiel #19
0
 def test_insert_before_return_new_item(self):
     ll = LinkedList()
     item1 = ll.add_to_front(5151, 91951)
     key = 123
     value = [1,2,3]
     item2 = ll.insert_before(item1, key, value)
     assert item2.key == key
     assert item2.value == value
Beispiel #20
0
 def test_swap_preserves_length(self):
     ll = LinkedList()
     item1 = ll.add_to_front(5151, 91951)
     assert ll.length == 1
     item2 = ll.add_to_front(235151, 91951)
     assert ll.length == 2
     ll.swap(item1, item2)
     assert ll.length == 2
Beispiel #21
0
 def test_filter_creates_new_items(self):
     ll = LinkedList()
     item1 = ll.add_to_front(12, 3534536)
     ll2 = ll.filter(None)
     item2 = ll2.front
     assert item1 != item2
     assert item1.key == item2.key
     assert item2.value == item2.value
Beispiel #22
0
 def test_add_back_appends_item(self):
     '''Adding to the back of the list multiple times does not remove items.
     Instead the list is appended with the new item'''
     ll = LinkedList()
     ll.add_to_back(12, 345)
     ll.add_to_back(14, 34)
     assert ll.back.key == 14
     assert ll.back.prev.key == 12
Beispiel #23
0
 def test_add_front_prepends_item(self):
     '''Adding to the front of the list multiple times does not remove items.
     Instead the list is prepended with the new item'''
     ll = LinkedList()
     ll.add_to_front(12, 54)
     ll.add_to_front(14, 98)
     assert ll.front.key == 14
     assert ll.front.next.key == 12
Beispiel #24
0
 def test_add_front_multiple_equal_items(self):
     '''Adding the same item to the front of the list multiple times creates
     different linked list objects with the same item'''
     ll = LinkedList()
     ll.add_to_front(12)
     ll.add_to_front(12)
     assert ll.front.key == ll.front.next.key 
     assert ll.front != ll.front.next 
Beispiel #25
0
 def test_insert_before(self):
     llist = LinkedList()
     for i in xrange(10):
         llist.push_back(i)
     for item in llist:
         if item.value % 2 == 0:
             llist.insert_before(item, item.value)
     self.assertEqual([0,0,1,2,2,3,4,4,5,6,6,7,8,8,9], [node.value for node in llist])
def main():
    ll = LinkedList()
    data = [char for char in 'FOLLOW UP']
    for char in data[::-1]:
        node = Node(char)
        ll.insert(node)
    remove_duplicates(ll.head)
    print "%s" % ll == "%s" % ['F', 'O', 'L', 'W', ' ', 'U', 'P']
def main():
    ll = LinkedList()
    data = [char for char in '123456789']
    for char in data[::-1]:
        node = Node(char)
        ll.insert(node)
    print ll
    print ll.size()
    print kth_tolast(ll.head, 5).val == '123456789'[-5]
Beispiel #28
0
 def test_find_last_finds_last(self):
     ll = LinkedList()
     key = 123
     value1 = 441
     value2 = "sdsfgg"
     ll.add_to_front(key, value1)
     ll.add_to_front(key, value2)
     item = ll.find_last(key)
     assert item.value == value1
Beispiel #29
0
 def test_add_to_front_prev(self):
     '''Add to front places previous front after the new front'''
     ll = LinkedList()
     key1 = 123
     key2 = 1233
     ll.add_to_front(key1)
     ll.add_to_front(key2)
     assert ll.front.next.key == key1
     assert ll.front.next.prev.key == key2
Beispiel #30
0
class Stack(object):
    def __init__(self,top=None):
        self.ll = LinkedList(top)

    def push(self, new_element):
        self.ll.insert_first(new_element)

    def pop(self):
        return self.ll.delete_first()
 def __init__(self):
     self.items = LinkedList()
Beispiel #32
0
        "<-------------------Sweepstakes---------------------------------------->"
    )
    test3 = Sweepstakes()
    test3.sweepstatkes_signup("sixth", "six")
    test3.find_a_winner()
    print(
        "<-------------------Family Dictionary---------------------------------------->"
    )
    test4 = Familymembers()
    test4.print_family()

    print(
        "<-------------------LinkedList---------------------------------------->"
    )

    linked_list = LinkedList()

    linked_list.append_node(55)
    linked_list.append_node(60)
    linked_list.append_node(65)
    linked_list.append_node(70)
    linked_list.append_node(75)
    linked_list.append_node(80)
    linked_list.add_to_beginning(30)
    linked_list.contains_node()
    print(
        "<-------------------BinaryTree---------------------------------------->"
    )

    tree = Binarytree()
    tree.add_to_tree(50)
def set_up(l1, l2):

    intersecting_node = Node(5)
    intersecting_node.next = Node(6)
    intersecting_node.next.next = Node(7)

    l1tail = l1.head
    l2tail = l2.head

    while l1tail.next is not None:
        l1tail = l1tail.next

    l1tail.next = intersecting_node

    while l2tail.next is not None:
        l2tail = l2tail.next

    l2tail.next = intersecting_node


l1 = LinkedList()
l2 = LinkedList()
l1.add_multiple([1, 2, 3, 4])
l2.add_multiple([9, 2])

set_up(l1, l2)

print("The intersecting node contains the value:",
      intersection(l1, l2))  # This returns the intersecting node but the
# __str__ function forces the return of the node value
Beispiel #34
0
class LinkedStack(object):

    def __init__(self, iterable=None):
        """Initialize this stack and push the given items, if any."""
        # Initialize a new linked list to store the items
        self.list = LinkedList()
        if iterable is not None:
            for item in iterable:
                self.push(item)

    def __repr__(self):
        """Return a string representation of this stack."""
        return 'Stack({} items, top={})'.format(self.length(), self.peek())

    def is_empty(self):
        """Return True if this stack is empty, or False otherwise."""
        # TODO: Check if empty
        return self.list.is_empty()

    def length(self):
        """Return the number of items in this stack."""
        # TODO: Count number of items
        return self.list.length()

    def push(self, item):
        """Insert the given item on the top of this stack.
        Running time: O(???) – Why? [TODO]
        the time complexity of this function is O(1) constant time because for a linked list
        appending an item takes just a few actions that are not reliant on the number of entries
        in the linked list
        """
        # TODO: Push given item
        self.list.prepend(item)

    def peek(self):
        """Return the item on the top of this stack without removing it,
        or None if this stack is empty.
        this function takes constant time O(1) because accessing the head node of a linked
        list takes constant time. Traversing a linked list takes O(n) but because the target node is
        always the head node then it takes constant time
        """
        # TODO: Return top item, if any
        if self.is_empty():
            return None
        else:
            return self.list.head.data

    def pop(self):
        """Remove and return the item on the top of this stack,
        or raise ValueError if this stack is empty.
        Running time: O(???) – Why? [TODO]
        This function takes O(n) time every time because the linked list's
        delete function is called to delete the node but that means that
        function call will traverse the entire linked list until it gets to 
        the tail. The LL delete function's worst case running time is O(n) and 
        the way it is being called here means it will always hit the worst
        case running time
        """
        # TODO: Remove and return top item, if any
        if self.list.head:
            top_data = self.list.head.data
            self.list.delete(top_data)
            return top_data
        else:
            raise ValueError("stack empty")
Beispiel #35
0
 def test_find(self):
     ll = LinkedList(['A', 'B', 'C'])
     assert ll.find(lambda item: item == 'B') == 'B'  # Match equality
     assert ll.find(lambda item: item < 'B') == 'A'  # Match less than
     assert ll.find(lambda item: item > 'B') == 'C'  # Match greater than
     assert ll.find(lambda item: item == 'X') is None  # No matching item
Beispiel #36
0
 def test_delete_with_3_items(self):
     ll = LinkedList(['A', 'B', 'C'])
     assert ll.head.data == 'A'  # First item
     assert ll.tail.data == 'C'  # Last item
     ll.delete('A')
     assert ll.head.data == 'B'  # New head
     assert ll.tail.data == 'C'  # Unchanged
     ll.delete('C')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'B'  # New tail
     ll.delete('B')
     assert ll.head is None  # No head
     assert ll.tail is None  # No tail
     # Delete should raise error if item was already deleted
     with self.assertRaises(ValueError):
         ll.delete('A')  # Item no longer in list
     with self.assertRaises(ValueError):
         ll.delete('B')  # Item no longer in list
     with self.assertRaises(ValueError):
         ll.delete('C')  # Item no longer in list
 def test_find(self):
     ll = LinkedList(['A', 'B', 'C'])
     assert ll.find('B') == 'B'  # Match equality
     assert ll.find('C') == 'C'  # Match equality
     assert ll.find('X') is None  # No matching item
Beispiel #38
0
 def test_delete_with_5_items(self):
     ll = LinkedList(['A', 'B', 'C', 'D', 'E'])
     assert ll.head.data == 'A'  # First item
     assert ll.tail.data == 'E'  # Last item
     ll.delete('A')
     assert ll.head.data == 'B'  # New head
     assert ll.tail.data == 'E'  # Unchanged
     ll.delete('E')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'D'  # New tail
     ll.delete('C')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'D'  # Unchanged
     ll.delete('D')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'B'  # New tail
     ll.delete('B')
     assert ll.head is None  # No head
     assert ll.tail is None  # No tail
Beispiel #39
0
 def test_init(self):
     ll = LinkedList()
     # Initializer should add instance properties
     assert ll.head is None  # First node
     assert ll.tail is None  # Last node
Beispiel #40
0
 def test_length_after_delete(self):
     ll = LinkedList(['A', 'B', 'C', 'D', 'E'])
     assert ll.length() == 5
     # Delete should decrease length
     ll.delete('A')
     assert ll.length() == 4
     ll.delete('E')
     assert ll.length() == 3
     ll.delete('C')
     assert ll.length() == 2
     ll.delete('D')
     assert ll.length() == 1
     ll.delete('B')
     assert ll.length() == 0
 def __init__(self, init_size=8):
     """Initialize this hash table with the given initial size."""
     self.buckets = [LinkedList() for i in range(init_size)]
     self.size = 0  # Number of key-value entries
 def __init__(self, init_size=8):
     """Initialize this hash table with the given initial size."""
     # Create a new list (used as fixed-size array) of empty linked lists
     self.buckets = [LinkedList() for _ in range(init_size)]
Beispiel #43
0
    def test_list_creation(self):
        linked_list = LinkedList()

        self.assertIsNone(linked_list.get_root())
Beispiel #44
0
class Queue():
    """A queue. FIFO.

    Operations: enqueue(item), dequeue(), peek(), is_empty()

    Make a queue:

        >>> karaoke_playlist = Queue()

    Anything in the queue?

        >>> karaoke_playlist.is_empty()
        True

    If there's nothing in the karaoke queue, how can we sing like crazy
    people? Let's add songs.

        >>> karaoke_playlist.enqueue("Try Everything -- Shakira")
        >>> karaoke_playlist.enqueue("Sing -- Pentatonix")
        >>> karaoke_playlist.enqueue("Best Day of My Life -- American Authors")

    Anything in the queue now?

       >>> karaoke_playlist.is_empty()
       False

    Sweeeet. Now we can belt some tunes. Which song is first?

       >>> karaoke_playlist.peek()
       'Try Everything -- Shakira'

    Let's sing it!

       >>> song = karaoke_playlist.dequeue()

    Are we singing the right song?

       >>> print(f"Now singing: {song}")
       Now singing: Try Everything -- Shakira

    Looks about right. What's next?

       >>> karaoke_playlist.peek()
       'Sing -- Pentatonix'

    We can take a break now...

    But let's see how our repr comes out, anyway.

       >>> print(karaoke_playlist)
       <Queue Front: Sing -- Pentatonix>
    """
    def __init__(self):
        """Initialize queue."""

        self.items = LinkedList()

    def __repr__(self):
        """A human-readable representation of the queue instance."""

        return f"<Queue Front: {self.peek()}>"

    def is_empty(self):
        """Return True if no items in queue. Return False otherwise."""

        return self.items.head is None

    def enqueue(self, item):
        """Place an item at the back of the queue."""

        self.items.append(item)

    def dequeue(self):
        """Remove the item at the front of the queue and return it."""

        front_item = self.items.head

        self.items.remove(self.items.head.data)

        return front_item.data

    def peek(self):
        """Check the item at the front of the queue and return it."""

        return self.items.head.data
Beispiel #45
0
 def test_delete_with_item_not_in_list(self):
     ll = LinkedList(['A', 'B', 'C'])
     # Delete should raise error if item not found
     with self.assertRaises(ValueError):
         ll.delete('X')  # Item not found in list
 def __init__(self, init_size=8):
     """Create a new list (used as fixed-size array) of empty linked lists"""
     """Initialize this hash table with the given initial size."""
     self.buckets = [LinkedList() for i in range(init_size)]
     self.size = 0  # Number of key-value entries
Beispiel #47
0

def sort_linked_list(linked_list):
    print("\n---------------------------")
    print("The original linked list is:\n{0}".format(
        linked_list.stringify_list()))
    new_linked_list = LinkedList()
    while linked_list.get_head_node():
        max_val = find_max(linked_list)
        new_linked_list.insert_beginning(max_val)
        linked_list.remove_node(max_val)
    return new_linked_list


#Test Cases for sort_linked_list
ll = LinkedList("Z")
ll.insert_beginning("C")
ll.insert_beginning("Q")
ll.insert_beginning("A")
print("The sorted linked list is:\n{0}".format(
    sort_linked_list(ll).stringify_list()))

ll_2 = LinkedList(1)
ll_2.insert_beginning(4)
ll_2.insert_beginning(18)
ll_2.insert_beginning(2)
ll_2.insert_beginning(3)
ll_2.insert_beginning(7)
print("The sorted linked list is:\n{0}".format(
    sort_linked_list(ll_2).stringify_list()))
Beispiel #48
0
 def test_length_after_append_and_prepend(self):
     ll = LinkedList()
     assert ll.length() == 0
     # Append and prepend should increase length
     ll.append('C')
     assert ll.length() == 1
     ll.prepend('B')
     assert ll.length() == 2
     ll.append('D')
     assert ll.length() == 3
     ll.prepend('A')
     assert ll.length() == 4
from linkedlist import Node, LinkedList


def deleteMiddleNode(input_list, del_node):
    node = input_list.head
    if not node or not node.next:
        return

    while (node.next != del_node):
        node = node.next
    node.next = del_node.next


# TESTS
my_list = LinkedList()

for elem in ['a', 'b', 'c', 'd', 'e', 'f']:
    my_list.append(elem)

print("Before: ")
my_list.printList()

deleteMiddleNode(my_list, my_list.head.next.next)
print("After: ")
my_list.printList()

# This solution is O(n) time and O(1) space
Beispiel #50
0
 def test_length_after_prepend(self):
     ll = LinkedList()
     assert ll.length() == 0
     # Prepend should increase length
     ll.prepend('C')
     assert ll.length() == 1
     ll.prepend('B')
     assert ll.length() == 2
     ll.prepend('A')
     assert ll.length() == 3
Beispiel #51
0
    def __init__(self, iterable=None):

        self.list = LinkedList()
        if iterable is not None:
            for item in iterable:
                self.enqueue_back(item)
Beispiel #52
0
 def test_items_after_prepend(self):
     ll = LinkedList()
     assert ll.items() == []
     # Prepend should add new item to head of list
     ll.prepend('C')
     assert ll.items() == ['C']
     ll.prepend('B')
     assert ll.items() == ['B', 'C']
     ll.prepend('A')
     assert ll.items() == ['A', 'B', 'C']
Beispiel #53
0
from linkedlist import LinkedList
from node import Node
import os

list = LinkedList()

node1 = Node('Bryan')
node2 = Node(18)
node3 = Node(True)
node4 = Node(3.40)


node1.next = node2
node2.next = node3
node3.next = node4

list.head = node1
list.tail = node4

def before_after(list):
	os.system('clear')
	print("		----- BEFORE -----\n")
	list.show()
	print("\n		Run...\n")
	list.insert("Test", 1)
	print("\n\n		----- AFTER -----\n")
	list.show()

before_after(list)
Beispiel #54
0
 def test_items_after_append(self):
     ll = LinkedList()
     assert ll.items() == []
     # Append should add new item to tail of list
     ll.append('A')
     assert ll.items() == ['A']
     ll.append('B')
     assert ll.items() == ['A', 'B']
     ll.append('C')
     assert ll.items() == ['A', 'B', 'C']
Beispiel #55
0
class LinkedDeque(object):
    def __init__(self, iterable=None):

        self.list = LinkedList()
        if iterable is not None:
            for item in iterable:
                self.enqueue_back(item)

    def is_empty(self):
        return self.list.size == 0

    def front(self):
        ''' Returns the element in the front of the queueu 
            Worst Case Runtime - O(1) since the front of the queue is the head of the linkedlist
        '''

        if self.is_empty():
            return None

        return self.list.head.data

    def length(self):

        return self.list.size

    def enqueue_front(self, item):
        ''' Adds an item in the front of the queue.
            Worst Case Runtime : O(1) O(1) since we're just preppending
        '''
        self.list.prepend(item)

    def enqueue_back(self, item):
        ''' Add an item in the back of the queue.
            Worst Case Runtime : O(1) since we're just appending
        '''
        self.list.append(item)

    def dequeue_front(self):
        ''' Pops and returns the element in the front of the queue.
            Worst Case Runtime : O(1) since we just re-arrange the head's pointer
        '''

        if self.is_empty():
            raise ValueError("Empty Queue")

        item = self.list.head.data

        if self.list.head == self.list.tail:
            self.tail = self.head = None
        else:
            self.list.head = self.list.head.next

        self.list.size -= 1
        return item

    def dequeue_back(self):
        ''' Pops and returns the element on the back of the queue.
            Worst Case Runtime : O(n) since we must re-arrange the tail's pointer
        '''

        if self.is_empty():
            raise ValueError("Empty queue")

        if self.list.tail:
            item = self.list.tail.data

        curr = self.list.head
        while curr is not None:
            if curr.next == self.list.tail:
                self.tail = curr
                self.tail.next = None
            curr = curr.next

        self.list.size -= 1
        return item
Beispiel #56
0
 def test_init_with_list(self):
     ll = LinkedList(['A', 'B', 'C'])
     # Initializer should append items in order
     assert ll.head.data == 'A'  # First item
     assert ll.tail.data == 'C'  # Last item
Beispiel #57
0
 def __init__(self, init_size=2000):
     """Initialize this hash table with the given initial size"""
     self.buckets = [LinkedList() for i in range(init_size)]
Beispiel #58
0
    def test_find_missing_in_list(self):
        linked_list = LinkedList()

        with self.assertRaises(LookupError):
            linked_list.find("Smith")
Beispiel #59
0
# https://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/
# Middle of linked list

import sys
sys.path.append('/home/sarthak/code/DataStructures/Linked_Lists')
from linkedlist import LinkedList

ll = LinkedList(12)
ll.add(27)
ll.add(29)
ll.add(39)
ll.add(49)
ll.add(59)
ll.add(69)
ll.add(40)


def middle(ll):
    head = ll.head
    mid = head

    while head != None:
        mid = mid.next
        head = head.next.next

    return mid


ll.printAll()
print("=============")
print middle(ll).data
Beispiel #60
0
    def __init__(self):
        """Initialize queue."""

        self.items = LinkedList()