コード例 #1
0
    def test_list_count(self):
        lst = SinglyLinkedList()
        self.assertEqual(lst.size(), 0, " Count should be 0")

        lst.add("some data")
        self.assertEqual(lst.size(), 1, " Count should be 1")

        lst.add("some more data")
        self.assertEqual(lst.size(), 2, " Count should be 2")
コード例 #2
0
def testSize1to2():
    _list = SinglyLinkedList()
    _list.push_front(4)

    assert _list.size() == 1

    _list.push_front(9)
    assert _list.size() == 2
コード例 #3
0
def testEraseLast():
    _list = SinglyLinkedList()
    _list.push_back(44)
    _list.push_back(55)
    _list.erase(1)

    assert _list.size() == 1
    assert _list.front() == 44
コード例 #4
0
class Queue(object):
    """ Queue class """
    def __init__(self):
        self._list = SinglyLinkedList()

    def is_empty(self):
        """ bool returns true if empty """
        return self._list.is_empty()

    def enqueue(self, value):
        """ adds value at position at tail """
        self._list.push_back(value)

    def dequeue(self):
        """ returns value and removes least recently added element (front) """
        return self._list.pop_front()
コード例 #5
0
def reverse_list(linked_list: SinglyLinkedList):

    current_node = linked_list.head

    previous_node = None

    next_node = None

    while current_node != None:

        # logic
        # 1. current nodes next node will be
        #    previous node
        #
        #
        #
        #

        # get current node's next
        next_node = current_node.get_next()

        # current_node's next is previous node
        current_node.set_next(previous_node)

        # previous node
        previous_node = current_node

        # loop increment
        current_node = next_node

        # reset list
        linked_list.head = \
        previous_node

    return linked_list
コード例 #6
0
def testValueNFromEnd():
    _list = SinglyLinkedList()
    _list.push_back(44)
    _list.push_back(55)
    _list.push_back(66)

    assert _list.value_n_from_end(1) == 66
    assert _list.value_n_from_end(2) == 55
    assert _list.value_n_from_end(3) == 44
コード例 #7
0
def testReverseTwo():
    _list = SinglyLinkedList()
    _list.push_back(44)
    _list.push_back(55)

    _list.reverse()

    assert _list.front() == 55
    assert _list.back() == 44
コード例 #8
0
class Queue(object):
    lstInstance = SinglyLinkedList()

    def dequeue(self):
        return self.lstInstance.removeAt(0)

    def enqueue(self, value):
        self.lstInstance.insertAt(value, self.lstInstance.getSize())
コード例 #9
0
class Stack(object):
    lstInstance = SinglyLinkedList()

    def pop(self):
        return self.lstInstance.removeAt(0)

    def push(self, value):
        self.lstInstance.insertAt(value, 0)
コード例 #10
0
def testReverseOne():
    _list = SinglyLinkedList()
    _list.push_back(44)

    _list.reverse()

    assert _list.front() == 44
コード例 #11
0
def isPalindrome(ll):
    slow = ll.getHead()
    fast = ll.getHead()
    aux1 = SinglyLinkedList()
    while fast != None:
        fast = fast.get_next()
        if fast == None:
            break
        fast = fast.get_next()
        slow = slow.get_next()
    if len(ll) % 2 == 0:
        fast = slow.get_next()
        slow = ll.getHead()
        while slow != fast:
            aux1.insert_at_beginning(slow.get_data())
            slow = slow.get_next()
    else:
        fast = slow.get_next()
        slow = ll.getHead()
        while slow.get_next() != fast:
            aux1.insert_at_beginning(slow.get_data())
            slow = slow.get_next()

    slow = aux1.getHead()
    while slow and fast:
        if slow.get_data() != fast.get_data():
            return False
        slow = slow.get_next()
        fast = fast.get_data()
    return True
コード例 #12
0
class LinkedListStack:
    def __init__(self, limit):
        self.limit = limit
        self.sll = SinglyLinkedList()
        self.length = 0

    def extend_limit(self, percent):
        self.limit = int((1 + percent / 100) * self.limit)

    def push(self, data):  #
        self.sll.append(data)
        self.length += 1

    def pop(self):
        self.sll.delete(self.length - 1)
        self.length -= 1

    def display(self):
        self.sll.display()

    def lookup(self, data):
        return self.sll.lookup(data)

    def peek(self):
        return self.sll.head.data
コード例 #13
0
 def __init__(self, keyComparator: Comparator = None, valueComparator: Comparator = None, size: int = 10):
     self.buckets = [None] * size
     firstTempIndex: int = 0
     while firstTempIndex < size:
         self.buckets[firstTempIndex] = SinglyLinkedList()
         firstTempIndex += 1
     self.currentSize = 0
     self.keyComparator = keyComparator
     self.valueComparator = valueComparator
コード例 #14
0
def main():

    mylist = SinglyLinkedList()
    mylist.insert_node(1)
    mylist.insert_node(2)
    mylist.insert_node(3)
    mylist.insert_node(4)
    mylist.insert_node(2)
    mylist.insert_node(1)

    print(isPalindrome(mylist))
コード例 #15
0
ファイル: Main.py プロジェクト: clarkmyfancy/Data-Structures
def main():
    x = SinglyLinkedList()
    n0 = Node(123542634263)
    n1 = Node(-1)
    n2 = Node(0)
    n3 = Node()
    n4 = Node(312.2134)

    x.push(n0)
    x.push(n1)
    x.push(n2)
    x.push(n3)
    x.push(n4)

    print(x.pretty_print())
コード例 #16
0
    def internalNodes(self, node = -1):
        # Consider some edge cases ...
        if node == -1:
            node = self.root

        # Begin to prepare results list
        results = SinglyLinkedList()

        # If we have any children
        if node.left is not None or node.right is not None:
            results.append(node.key)

        # Perform deeper recursions only where valid
        if node.left is not None:
            results += self.internalNodes(node.left)

        if node.right is not None:
            results += self.internalNodes(node.right)

        return results
コード例 #17
0
def test_nth_to_last_node():

    a = SinglyLinkedList()

    a.add(1)
    a.add(2)
    a.add(3)
    a.add(4)
    a.add(5)
    a.add(6)

    print("test_nth_to_last_node")
    print(nth_to_last_node(a, 2))  # 5
コード例 #18
0
class PriorityQueue:
    list = ''

    def __init__(self):
        self.list = SinglyLinkedList()

    def enqueueWithPriority(self, value, priority):
        idxInsert = 0
        for itr in range(self.list.getSize()):
            node = self.list.get(itr)
            if node.getValue() == '':
                idxInsert = itr
                break
            if node.getValue().getPriority() < priority:
                idxInsert = itr
                break
            else:
                idxInsert = itr + 1
        self.list.insertAt(PriorityNode(value, priority), idxInsert)

    def dequeueWithPriority(self):
        return self.list.removeAt(0).getValue()
コード例 #19
0
def testPopBack():
    _list = SinglyLinkedList()
    _list.push_back(33)
    _list.push_back(36)

    assert _list.pop_back() == 36
    assert _list.pop_back() == 33
    assert _list.size() == 0
コード例 #20
0
def testPushBack():
    _list = SinglyLinkedList()
    _list.push_back(123)
    _list.push_back(456)

    assert _list.size() == 2
    assert _list.value_at(0) == 123
    assert _list.value_at(1) == 456
コード例 #21
0
def testPushFront():
    _list = SinglyLinkedList()
    _list.push_front(753)
    _list.push_front(159)

    assert _list.size() == 2
    assert _list.value_at(0) == 159
    assert _list.value_at(1) == 753
コード例 #22
0
ファイル: play.py プロジェクト: maneeshd/algo-ds
def iter_reverse(l: SinglyLinkedList) -> None:
    """Reverse a given linked list in-place.

    :param l: A singly linked list class object
    :type l: SinglyLinkedList
    """
    pre = None
    cur = l.head
    nxt = None
    while cur:
        nxt = cur.next
        cur.next = pre
        pre = cur
        cur = nxt
    l.head = pre
コード例 #23
0
def nth_to_last_node(linked_list: SinglyLinkedList, nth_index: int):

    size = linked_list.size()

    # edge case
    if nth_index > size:
        return None

    # + 1 as we need the exact index
    # eg:
    """
    1->2->3->4

    size = 4

    n = 1

    index = size - n = 4-1 = 3
    
    we need 1st index from bottom.. so 4
    
    hence index = (size - n) + 1
    
    ideally index = size - (n-1)
    
    """
    index = (size - (nth_index - 1))

    count = 0

    current_node = linked_list.head

    while current_node != None:

        count += 1

        if count == index:

            return current_node.get_value()

        else:

            current_node = \
            current_node.get_next()
def test_cycle():

    a = SinglyLinkedList()

    a.add(1)
    a.add(2)
    a.add(3)

    predecessor = \
    a.predecessor(2) #2

    # set 3's next as 2
    a.tail.set_next(predecessor)

    #printSinglyLinkedList(a)

    print("test_cycle")
    print(cycle_check(a))
コード例 #25
0
def sum_lists(ll1, ll2):
    new_ll = SinglyLinkedList()
    current1 = ll1.head
    current2 = ll2.head
    carry, result = 0, 0
    while (current1 != None and current2 != None):
        res = carry
        res += current1.value + current2.value
        carry = (res - (res % 10)) // 10
        res = res % 10
        new_ll.insert_node(res)
        current1 = current1.next
        current2 = current2.next

    new_ll.print_linkedlist()
コード例 #26
0
def list_reversal(linked_list: SinglyLinkedList):
    """
  Logic
  -----

  current_node->next = current_node->previous_node

   1->2->3->4

   1<-2<-3<-4 

  """

    # Loop

    current_node = linked_list.head

    previous_node = None

    next_node = None

    while current_node != None:

        # cache next node
        next_node = current_node.get_next()

        # current_node->next = current_node->previous_node
        current_node.set_next(previous_node)

        #previous node
        previous_node = current_node

        # lopp increment
        current_node = next_node

    linked_list.head = previous_node

    return linked_list
コード例 #27
0
    def descendants(self, E, node=-1, parentFound = False):
        # Consider some edge cases ...
        if node == -1:
            node = self.root

        # If the value is not found, it returns null
        if not self.contains(E):
            return None

        if node is None:
            return None


        # Begin to prepare results list
        results = SinglyLinkedList()

        # Activate parentFound flag, meaning that we are ready to start adding data
        if node.key == E:
            parentFound = True

        # PERFORM PRE-ORDER TRAVERSAL

        # If key E was already found, append new stuff to results ...
        if parentFound:
            results = SinglyLinkedList()
            results.append(node.key)

        # Pass down results from deeper recursions
        left_results = self.descendants(E, node.left, parentFound)
        right_results = self.descendants(E, node.right, parentFound)

        if left_results is not None:
            results += left_results

        if right_results is not None:
            results += right_results

        return results
コード例 #28
0
def sum_lists_followup(ll1, ll2):
    s1, s2 = ll1.get_size(), ll2.get_size()
    current1 = ll1.head
    current2 = ll2.head
    new_list = SinglyLinkedList()
    if (s1 != s2):
        #If their size is not equal first pad zeros to the shorter one
        if (s1 > s2):
            for i in range(s1 - s2):
                ll2.insert_beginning(0)
        else:
            for i in range(s1 - s2):
                ll1.insert_beginning(0)
    else:

        result = 0
        while (current1 != None and current2 != None):
            result = (result * 10) + current1.value + current2.value
            current1 = current1.next
            current2 = current2.next
        for i in str(result):
            new_list.insert_node(int(i))

        new_list.print_linkedlist()
コード例 #29
0
 def makeEmpty(self):
     tempIndex: int = 0
     while tempIndex < len(self.buckets):
         self.buckets[tempIndex] = SinglyLinkedList()
         tempIndex += 1
     self.currentSize = 0
コード例 #30
0
 def __init__(self, param=None):
     if param is None:
         self.linked_list = SinglyLinkedList()
     else:
         self.linked_list = SinglyLinkedList(param)
コード例 #31
0
ファイル: tester.py プロジェクト: asasine/data-structures
from SinglyLinkedList import SinglyLinkedList as SLL

print("Testing SinglyLinkedList")
sll = SLL()
print("List size:", sll.size)

print()
print("Testing insert")
for i in range(3):
    print("Inserting {0}: success={1}".format(i, sll.insert(i)))
print("List contains:", sll.print())
print()

print("Testing contains")
for i in range(4):
    print("List contains {0}: success={1}".format(i, sll.contains(i)))
print("List contains:", sll.print())
print()

print("Testing remove")
nums = [3, 1, 0, 2]
for i in nums:
    print("Removing {0}: success={1}".format(i, sll.remove(i)))
print("List contains:", sll.print())
print()