def test_rec_merge():
    # 测试link1为空链表
    link1 = LinkedList()
    link2 = LinkedList()
    link2.append(1)
    assert rec_merge(link1.root, link2.root) == link2.root

    # 测试link2为空链表
    link1 = LinkedList()
    link1.append(1)
    link2 = LinkedList()
    assert rec_merge(link1.root, link2.root) == link1.root

    # 测试两个空链表
    link1 = LinkedList()
    link2 = LinkedList()
    assert rec_merge(link1.root, link2.root) == link2.root

    # 测试两个完整的链表
    link1 = LinkedList()
    link2 = LinkedList()
    link1.append(1)
    link1.append(3)
    link2.append(2)
    link2.append(4)
    link2.append(4)
    link2.append(5)
    print(rec_merge(link1.root, link2.root).value)
    print(rec_merge(link1.root, link2.root).value)
def test_insert_after():
    initialList = LinkedList()
    initialList.append(5)
    initialList.append(6)
    initialList.append(7)
    initialList.insertAfter(8, 7)
    assert str(initialList) == '5 ->6 ->7 ->8'
def test_merge():
    # 测试link1为空链表
    link1 = LinkedList()
    link2 = LinkedList()
    link2.append(1)
    assert merge(link1.root, link2.root) == link2.root

    # 测试link2为空链表
    link1 = LinkedList()
    link1.append(1)
    link2 = LinkedList()
    assert merge(link1.root, link2.root) == link1.root

    # 测试两个空链表
    link1 = LinkedList()
    link2 = LinkedList()
    assert merge(link1.root, link2.root) == link2.root

    # 测试两个完整的链表
    link1 = LinkedList()
    link2 = LinkedList()
    link1.append(1)
    link1.append(3)
    link2.append(2)
    link2.append(4)
    link2.append(4)
    link2.append(5)
    assert list(merge(link1.root, link2.root)) == [1, 2, 3, 4, 4, 5]
def test_insert_before():
    initialList = LinkedList()
    initialList.append(6)
    initialList.append(7)
    initialList.append(8)
    initialList.insertBefore(5, 6)
    assert str(initialList) == '5 ->6 ->7 ->8'
def test_append():
    initialList = LinkedList()
    initialList.append(5)
    initialList.append(6)
    initialList.append(7)
    initialList.append(8)
    assert str(initialList) == '5 ->6 ->7 ->8'
Ejemplo n.º 6
0
 def test_remove_dups_no_buffer_t(self):
     ll_with_dups = LinkedList()
     ll_with_dups.append(2)
     ll_with_dups.append(2)
     ll_with_dups.append(2)
     ll_with_dups.remove_dups_no_buffer()
     self.assertEqual(ll_with_dups.to_s(), '2')
Ejemplo n.º 7
0
 def testLength(self):
     ll = LinkedList()
     self.assertEqual(ll.length(), 0)
     ll.append(1)
     ll.append(2)
     ll.append(3)
     self.assertEqual(ll.length(), 3)
Ejemplo n.º 8
0
def main():
    ll = LinkedList()

    print("Initial size: ", len(ll))
    ll.push(24)
    print("New size: ", len(ll))
    print("List content: ", ll)
    print("Pushing more")
    ll.push(6)
    ll.push(783)
    print("List content: ", ll)
    print("popping...")
    ll.pop()
    print("List content: ", ll)
    print("Does list contain 24?")
    if ll.contains(24):
        print("Yes")
    else:
        print("No")
    print("Deleting 24")
    ll.delete(24)
    print("List content: ", ll)
    print("Pushing another onto end.")
    ll.append(365)
    print("List content: ", ll)
Ejemplo n.º 9
0
 def testReturnLastNode(self):
     ll = LinkedList()
     self.assertEqual(ll.return_last_node(), None)
     ll.append(1)
     self.assertEqual(ll.return_last_node().data, 1)
     ll.append(2)
     self.assertEqual(ll.return_last_node().data, 2)
Ejemplo n.º 10
0
    class Node:
        """hash list node"""
        def __init__(self, data):
            self.connections = LinkedList()
            self.data = data

        def connect(self, node):
            """ returns next node"""
            if node:
                self.connections.append(node)

        def disconnect(self, node):
            """ det next node """
            if node:
                self.connections.remove(node)

        def get(self):
            """ returns node date """
            return self.data

        def __str__(self):
            connections = ''
            for node in self.connections:
                connections += f'[{node.data}] '
            return f'{self.data}: {connections}'
Ejemplo n.º 11
0
 def test_2(self):
     """test append method"""
     n1 = Node('A')
     link = LinkedList()
     link.append(n1)
     self.assertEqual(link._head._value, 'A')
     self.assertEqual(len(link), 1)
Ejemplo n.º 12
0
class Queue:
    """Linked List implementation of the Queue ADT"""
    def __init__(self):
        self.list = LinkedList()

    def __len__(self):
        return len(self.list)

    def push(self, data):
        node = Node(data)
        self.list.append(node)  # if this was prepend, we'd have a stack

    def pop(self):
        if self.is_empty():
            raise StopIteration("Attempting to pop from empty queue")
        node = self.list.head.data
        self.list.remove_head()
        return node

    def is_empty(self):
        return self.list.head is None

    def peek(self):
        return self.list.head.data

    def __str__(self):
        return str([data for _, data in self.list.traverse()])
Ejemplo n.º 13
0
 def test_4(self):
     """test that pop off only item in list that head becomes None"""
     n1 = Node('A')
     link = LinkedList()
     link.append(n1)
     link.pop()
     self.assertEqual(link._head, None)
Ejemplo n.º 14
0
 def test_get(self):
     l = LinkedList()
     self.assertIsNone(l.get(1))
     l.append(1)
     self.assertEqual(1, l.get(0))
     l.append(2)
     self.assertEqual(2, l.get(1))
Ejemplo n.º 15
0
def sum_lists(ll1,ll2):
    value1=value2=0

    pointer=ll1.head
    while pointer:
        value1=value1*10+pointer.data
        pointer=pointer.next

    pointer=ll2.head
    while pointer:
        value2=value2*10+pointer.data
        pointer=pointer.next

    result=value1+value2
    print value1,value2,result
    ll_sum=LinkedList()
    divider=10**(len(str(result))-1)
    while result:
        digit=result//divider
        ll_sum.append(digit)
        result=result%divider
        divider/=10

    #ll_sum.append(result)

    return ll_sum
Ejemplo n.º 16
0
 def test_print(self):
     test_list = LinkedList()
     test_list.append(1)
     test_list.append(2)
     test_list.append(3)
     test_list.append(2)
     self.assertEqual(test_list.to_s(), '1 2 3 2')
Ejemplo n.º 17
0
class Graph:
    """Adjacency list implementation of directed graph
    
    Linked list represents graph of nodes. Edges are represented as
    linked list of nodes indexes, connected to node.
    """
    def __init__(self):
        self.nodes = LinkedList()

    def __repr__(self):
        return "Graph" + repr(self.nodes)

    def insert(self, *links: int):
        """Add node with links """
        edges = LinkedList()
        for link in links:
            edges.append(link)
        self.nodes.append(edges)

    def lookup(self, node_index: int):
        """Return node using value"""
        return self.nodes.lookup(node_index)

    def delete(self, node_index: int):
        """Delete node and its references to other nodes"""

        # Delete references from other nodes
        for node in self.nodes:
            for index, link in enumerate(node.data):
                if link.data == node_index:
                    node.data.delete(index)

        # Delete node and its references
        self.nodes.delete(node_index)
Ejemplo n.º 18
0
    def test_is_empty(self):
        l = LinkedList()

        self.assertEqual(l.is_empty(), True)

        l.append("I don't wanna close my eyes...")
        self.assertEqual(l.is_empty(), False)
Ejemplo n.º 19
0
def test_append():
    ll = LinkedList()
    ll.insert('violet')
    ll.insert('indigo')
    ll.insert('blue')
    ll.append('green')
    assert ll.head.next.next.next.value =='green'
Ejemplo n.º 20
0
def zipLists(list1, list2):
    current_one = list1.head
    current_two = list2.head
    if current_one == None:
        return print(list2)
    if current_two == None:
        return print(list1)
    new_list = LinkedList()
    while current_one or current_two:
        if current_one:
            if new_list.head == None:
                new_list.insert(current_one.value)
            else:
                new_list.append(current_one.value)
        if current_two:
            if new_list.head == None:
                new_list.insert(current_two.value)
            else:
                new_list.append(current_two.value)
        if current_one and current_one.next:
            current_one = current_one.next
        else:
            current_one = False
        if current_two and current_two.next:
            current_two = current_two.next
        else:
            current_two = False
    return new_list
Ejemplo n.º 21
0
def test_str():
    linked_list = LinkedList()
    assert linked_list.__str__() == 'LinkedList []'

    linked_list.append('Alice')
    linked_list.append('Bob')
    assert linked_list.__str__() == """LinkedList [
Ejemplo n.º 22
0
def ll_merge(ll_one, ll_two):
    result_list = LinkedList()

    try:
        ll_one_current = ll_one.head
        ll_two_current = ll_two.head

        while ll_one_current is not None or ll_two_current is not None:
            # ll_one_next = ll_one_current._next
            # ll_two_next = ll_two_current._next

            if ll_one_current is not None:
                result_list.append(ll_one_current)
                ll_one_current = ll_one_current._next

            if ll_two_current is not None:
                result_list.append(ll_two_current)
                ll_two_current = ll_two_current._next

        result_list_current = result_list.head
        while result_list_current is not None:
            print(result_list_current)
            result_list_current = result_list_current._next
        # return result_list

        #     ll_one_current._next, ll_two_current._next = ll_two_next, ll_one_next
        #     ll_one_current = ll_one_next
        # ll_two.head = ll_two_current

    except None:
        'Not valid input'
Ejemplo n.º 23
0
def sum_two_list(self, llist):
    p = self.head
    q = self.head

    sum_list = LinkedList()

    carry = 0

    while p or q:
        if not p:
            i = 0
        else:
            i = p.data

        if not q:
            j = 0
        else:
            j = q.data

        s = i + j + carry

        if s >= 10:
            carry = 1
            remainder = s % 10
            sum_list.append(remainder)
        else:
            carry = 0
            sum_list.append(s)

        if p:
            p = p.next
        if q:
            q = q.next

        sum_list.print_llist()
Ejemplo n.º 24
0
 def test_append(self):
     """test_append: Test appending to a linked list
     """
     node1 = Node('test')
     lst = LinkedList()
     lst.append(node1)
     self.assertTrue(len(lst) == 1)
 def test_last_of_two_nodes(self):
     """
     In a two-node list, the second node is the last node.
     """
     ll = LinkedList()
     appendee = LinkedList(fake_value())
     ll.append(appendee)
     self.assertEqual(appendee, ll.last())
 def test_append_to_empty_list_sets_prev_of_sentinel_to_new_node(self):
     """
     Appending to an empty list sets the sentinel's `prev` to the new node.
     """
     ll = LinkedList()
     appendee = LinkedList(fake_value())
     ll.append(appendee)
     self.assertEqual(appendee, ll.prev)
 def test_list_with_two_nodes_is_not_empty(self):
     """
     A list with two nodes is not empty.
     """
     ll = LinkedList()
     appendee = LinkedList(fake_value())
     ll.append(appendee)
     self.assertFalse(ll.is_empty())
 def test_first_of_two_nodes_is_not_last(self):
     """
     In a two-node list, the first node is not last.
     """
     ll = LinkedList()
     appendee = LinkedList(fake_value())
     ll.append(appendee)
     self.assertFalse(ll.is_last())
 def test_second_of_two_nodes_is_last(self):
     """
     In a two-node list, the second node is last.
     """
     ll = LinkedList()
     appendee = LinkedList(fake_value())
     ll.append(appendee)
     self.assertTrue(appendee.is_last())
 def test_append_to_empty_list_sets_next_of_new_node_to_sentinel(self):
     """
     Appending to an empty list sets the new node's `next` to the sentinel.
     """
     ll = LinkedList()
     appendee = LinkedList(fake_value())
     ll.append(appendee)
     self.assertEqual(ll, appendee.next)
Ejemplo n.º 31
0
 def test_AppendLinkedList(self):
     linked_list = LinkedList()
     num_of_elements = 5
     for i in range(num_of_elements):
         linked_list.append(i)
     self.assertEquals(linked_list.size, num_of_elements)
     for i in range(num_of_elements):
         self.assertEquals(i, linked_list[i].data)
	def set(self, key, value):
		index = hash(key) % self.size

		if self.slots[index] == None:
			bucket = LinkedList()
			bucket.append([key, value])
			self.slots[index] = bucket
		else:
			self.slots[index].append((key, value))
Ejemplo n.º 33
0
 def test_linked_list_append(self):
     linked_list = LinkedList()
     linked_list.append(25)
     self.assertIsNotNone(linked_list)
     self.assertTrue(linked_list.__len__()==1)
     linked_list.append("Riccardo")
     self.assertTrue(linked_list.__len__()==2)
     self.assertTrue(linked_list.head.item==25)
     self.assertTrue(linked_list.head.next.item =="Riccardo")
     self.assertFalse(linked_list.head.next.item == "25")
Ejemplo n.º 34
0
 def test_linked_list_search(self):
     linked_list = LinkedList()
     linked_list.append(25)
     pos = linked_list.search(25)
     self.assertIsNotNone(linked_list)
     self.assertTrue(pos == 0)
     linked_list.append("Riccardo")
     pos = linked_list.search("Riccardo")
     self.assertEqual(pos,1)
     linked_list.insert_head("Prova")
     pos = linked_list.search("Prova")
     self.assertTrue(pos == 0)
Ejemplo n.º 35
0
    def test_LinkedList_append(self):
        l1 = LinkedList()
        l1.append(0)

        # ensure Node(0) added to list
        Node0 = l1.head
        self.assertEqual(Node0.val, 0)
        self.assertIsNone(Node0.link)

        # ensure Node(1) appended to back of list
        l1.append(1)
        Node0 = l1.head
        self.assertEqual(Node0.val, 0)
        self.assertIsNotNone(Node0.link)

        # ensure Node(0) is next in list
        Node1 = Node0.link
        self.assertEqual(Node1.val, 1)
        self.assertIsNone(Node1.link)

        # ensure adding 'None' adds something
        sz1 = l1.size()
        l1.append(None)
        self.assertEqual(sz1+1, l1.size())

        # ensure adding recursively adds nothing
        sz1 = l1.size()
        l1.append(l1)
        self.assertEqual(sz1, l1.size())
    def test_append(self):
        my_list = LinkedList()

        my_list.append(1)
        self.assertEqual(my_list.start.elem, 1)
        self.assertEqual(my_list.start.next, None)
        self.assertEqual(my_list, LinkedList([1]))

        my_list.append(2)
        self.assertEqual(my_list.start.elem, 1)
        self.assertEqual(my_list.start.next, Node(2))
        self.assertEqual(my_list.start.next.elem, 2)
        self.assertEqual(my_list.start.next.next, None)

        self.assertEqual(my_list.count(), 2)
Ejemplo n.º 37
0
class AssociativeArray:
    def __init__(self):
        self.items = LinkedList()

    def __unicode__(self):
        s = ''
        for key, value in self.items:
            s += repr(key) + ': ' + repr(value) + ', '
        return '{' + s + '}'

    __repr__ = __unicode__

    def put(self, key, value):
        for i, kv in enumerate(self.items):
            if kv[0] == key:
                l1 = self.items.take(i)
                l2 = self.items.drop(i + 1)
                self.items = l1.concat(l2)
                break
        self.items = self.items.append((key, value))

    def get(self, key):
        for k, v in self.items:
            if k == key:
                return v
Ejemplo n.º 38
0
    def test_ReverseLinkedList(self):
        linked_list = LinkedList()
        reversed_man_list = LinkedList()
        num_of_elements = 5
        for i in range(num_of_elements):
            linked_list.append(i)

        self.assertEquals(linked_list.size, num_of_elements)

        for i in range(num_of_elements-1, -1, -1):
            reversed_man_list.append(i)

        linked_list.reverse()

        for index, item in enumerate(linked_list):
            self.assertEquals(item.data, reversed_man_list[index].data)
Ejemplo n.º 39
0
def test_clear() -> None:
    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    node_4_data = {"id": 4}

    linked_list = LinkedList()
    linked_list.append(node_4_data)
    linked_list.append(node_3_data)
    linked_list.append(node_2_data)
    linked_list.append(node_1_data)

    linked_list.clear()

    assert linked_list.head is None
    assert linked_list.tail is None
Ejemplo n.º 40
0
def test_removing_elements() -> None:
    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    node_4_data = {"id": 4}
    linked_list = LinkedList()
    linked_list.append(node_1_data)
    linked_list.append(node_2_data)
    linked_list.append(node_3_data)
    linked_list.append(node_4_data)

    node_2 = linked_list.find(target_key="id", target_value=node_2_data["id"])
    linked_list.remove(node_2)
    assert linked_list.head is not None
    assert linked_list.head.data == node_1_data
    assert linked_list.head.next_node is not None
    assert linked_list.head.next_node.data == node_3_data
    assert linked_list.tail is not None
    assert linked_list.tail.data == node_4_data
    assert linked_list.tail.previous_node is not None
    assert linked_list.tail.previous_node.data == node_3_data

    node_1 = linked_list.find(target_key="id", target_value=node_1_data["id"])
    linked_list.remove(node_1)
    assert linked_list.head is not None
    assert linked_list.head.data == node_3_data
    assert linked_list.head.next_node is not None
    assert linked_list.head.next_node.data == node_4_data
    assert linked_list.tail is not None
    assert linked_list.tail.data == node_4_data
    assert linked_list.tail.previous_node is not None
    assert linked_list.tail.previous_node.data == node_3_data

    node_4 = linked_list.find(target_key="id", target_value=node_4_data["id"])
    linked_list.remove(node_4)
    assert linked_list.head is not None
    assert linked_list.head.data == node_3_data
    assert linked_list.head.next_node is None
    assert linked_list.tail is not None
    assert linked_list.tail.data == node_3_data
    assert linked_list.tail.previous_node is None

    node_3 = linked_list.find(target_key="id", target_value=node_3_data["id"])
    linked_list.remove(node_3)
    assert linked_list.head is None
    assert linked_list.tail is None
Ejemplo n.º 41
0
def main():
    linked_list = LinkedList()
    values = [5, 2, 7, 7, 33, 1, 6, 0, 4, 3]

    for num in values:
        linked_list.append(num)

    print(str(linked_list))

    # find 1st to last
    print(find_k_elem(linked_list.head, 1).value)
    # find 2nd to last
    print(find_k_elem(linked_list.head, 2).value)
    # find 6th to last
    print(find_k_elem(linked_list.head, 6).value)
    # find 33 to last elem
    print(find_k_elem(linked_list.head, 33))
class LinkedListTest(unittest.TestCase):
    def setUp(self):
        self.ll = LinkedList()
        for i in range(1, 6):
            self.ll.append(i)

    def test_creation(self):
        self.assertEqual(5, len(self.ll))

    def test_pop_value(self):
        self.assertEqual(1, self.ll.pop())

    def test_pop_length(self):
        self.ll.pop()
        self.assertEqual(4, len(self.ll))

    def test_push_value(self):
        self.ll.push(0)
        self.assertEqual(0, self.ll.get_head().value)

    def test_push_length(self):
        self.ll.push(0)
        self.assertEqual(6, len(self.ll))

    def test_remove_length(self):
        node = self.ll.get_head().next.next
        self.ll.remove(node)
        self.assertEqual(4, len(self.ll))

    def test_distinct(self):
        self.assertEqual([1, 2, 3, 4, 5], self.ll.distinct())

    def test_distinct_with_duplicate(self):
        self.ll.append(1)
        self.assertEqual([1, 2, 3, 4, 5], self.ll.distinct())

    def test_cycle_false(self):
        self.assertEqual(False, self.ll.has_cycle())

    def test_cycle_true(self):
        last_node = self.ll.get_tail()
        last_node.next = self.ll.get_head()
        self.assertEqual(True, self.ll.has_cycle())
Ejemplo n.º 43
0
def test_insert_after() -> None:
    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    node_4_data = {"id": 4}
    linked_list = LinkedList()
    linked_list.append(node_1_data)
    linked_list.append(node_2_data)

    node_1 = linked_list.find(target_key="id", target_value=node_1_data["id"])

    # Normal insert scenario
    linked_list.insert_after(data=node_3_data, node=node_1)

    assert linked_list.head.data == node_1_data
    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_3_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_2_data
    assert third_node.next_node is None
    assert linked_list.tail.data == node_2_data

    node_2 = linked_list.find(target_key="id", target_value=node_2_data["id"])

    # Insert at tail scenario
    linked_list.insert_after(data=node_4_data, node=node_2)

    assert linked_list.head.data == node_1_data
    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_3_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_2_data
    fourth_node = third_node.next_node
    assert fourth_node is not None
    assert fourth_node.data == node_4_data
    assert fourth_node.next_node is None
    assert linked_list.tail.data == node_4_data
Ejemplo n.º 44
0
def test_reversing_list() -> None:
    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    node_4_data = {"id": 4}
    linked_list = LinkedList()
    linked_list.append(node_1_data)
    linked_list.append(node_2_data)
    linked_list.append(node_3_data)
    linked_list.append(node_4_data)

    linked_list.reverse()

    assert linked_list.head is not None
    assert linked_list.head.data == node_4_data
    assert linked_list.head.previous_node is None

    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_3_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_2_data
    fourth_node = third_node.next_node
    assert fourth_node is not None
    assert fourth_node.data == node_1_data
    assert fourth_node.next_node is None

    assert linked_list.tail is not None
    assert fourth_node.data == linked_list.tail.data

    # Now go back to check previous links
    third_node = fourth_node.previous_node
    assert third_node is not None
    assert third_node.data == node_2_data
    second_node = third_node.previous_node
    assert second_node is not None
    assert second_node.data == node_3_data
    first_node = second_node.previous_node
    assert first_node is not None
    assert first_node.data == node_4_data
Ejemplo n.º 45
0
def add(list_a, list_b):
    list_c = LinkedList([0])

    node_a = list_a.head
    node_b = list_b.head
    node_c = list_c.head

    carry = 0
    while node_a or node_b:
        a = node_a.value if node_a else 0
        b = node_b.value if node_b else 0

        result = a + b + carry
        carry, result = divmod(result, 10)
        node_c.value = result
        if carry:
            list_c.append(carry)

        node_a = node_a.next_node if node_a else None
        node_b = node_b.next_node if node_b else None
        node_c = node_c.next_node

    return list_c
Ejemplo n.º 46
0
def test_finding_elements() -> None:
    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    other_data = {"id": 4}
    linked_list = LinkedList()
    linked_list.append(node_1_data)
    linked_list.append(node_2_data)
    linked_list.append(node_3_data)

    node = linked_list.find(target_key="id", target_value=node_1_data["id"])
    assert node is not None
    assert node.data == node_1_data

    node = linked_list.find(target_key="id", target_value=node_2_data["id"])
    assert node is not None
    assert node.data == node_2_data

    node = linked_list.find(target_key="id", target_value=node_3_data["id"])
    assert node is not None
    assert node.data == node_3_data

    assert linked_list.find(target_key="id", target_value=other_data["id"]) is None
    assert linked_list.find(target_key="inexistant_key", target_value="an_irrelevant_value") is None
Ejemplo n.º 47
0
class Queue:
    def __init__(self):
        self.items = LinkedList()

    @property
    def is_empty(self):
        """O(1)"""
        return self.items.is_empty

    def enqueue(self, x):
        """O(n) --> should be O(1)"""
        self.items = self.items.append(x)

    def dequeue(self):
        """O(1)"""
        if self.is_empty:
            raise UnderflowException
        else:
            x = self.items.head
            self.items = self.items.drop(1)
            return x
Ejemplo n.º 48
0
def add_lists(l1, l2):

	if (l1 is None) or (l2 is None) or ((l1.head is None) and (l2.head is None)):
		return None
	
	ll = LinkedList([])
	
	h = 0
	n1 = l1.head
	n2 = l2.head

	if n1 is not None: h += n1.data
	if n2 is not None: h += n2.data

	digit = h % 10
	remember = (h - (h % 10)) / 10
	ll.append(digit)

	while (n1 is not None) or (n2 is not None):
		h = 0
		if n1 is not None: n1 = n1.next
		if n2 is not None: n2 = n2.next
		if n1 is not None: h += n1.data
		if n2 is not None: h += n2.data
		
		h += remember
		digit = h % 10
		remember = (h - (h % 10)) / 10
		
		if (n1 is not None) or (n2 is not None):
			ll.append(digit)
		else:
			if digit > 0:
				ll.append(digit)
			if remember > 0:
				ll.append(remember)

	return ll
Ejemplo n.º 49
0
    def test_AddLinkedList(self):
        first = LinkedList()
        other = LinkedList()
        compare_list = LinkedList()
        num_of_elements = 5
        for i in range(num_of_elements):
            first.append(i)
            other.append(i)
            compare_list.append(i+i)

        self.assertEquals(first.size, num_of_elements)
        self.assertEquals(other.size, num_of_elements)

        res = first + other

        for index, item in enumerate(res):
            self.assertEquals(item.data, compare_list[index].data)
Ejemplo n.º 50
0
    def test_AddDecimalLinkedList_SameLength_NoCarry(self):
        first = LinkedList()
        second = LinkedList()
        compare_list = LinkedList()

        num_of_elements = 4
        for i in range(num_of_elements):
            first.append(i)
            second.append(i)
            compare_list.append(i+i)

        print(first)
        print(second)
        print(compare_list)

        res = first.add_as_decimal(second)

        for index, item in enumerate(res):
            self.assertEquals(item.data, compare_list[index].data)
Ejemplo n.º 51
0
def test_appending_elements() -> None:
    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    linked_list = LinkedList()

    linked_list.append(data=node_1_data)
    assert linked_list.head is not None
    assert linked_list.head.data == node_1_data
    assert linked_list.tail is not None
    assert linked_list.tail.data == node_1_data

    linked_list.append(data=node_2_data)
    assert linked_list.head.data == node_1_data
    assert linked_list.head.next_node is not None
    assert linked_list.head.next_node.data == node_2_data
    assert linked_list.head.previous_node is None
    assert linked_list.tail.data == node_2_data
    assert linked_list.tail.next_node is None
    assert linked_list.tail.previous_node is not None
    assert linked_list.tail.previous_node.data == node_1_data

    linked_list.append(data=node_3_data)
    assert linked_list.head.data == node_1_data
    assert linked_list.head.next_node is not None
    assert linked_list.head.next_node.data == node_2_data
    assert linked_list.head.previous_node is None
    assert linked_list.tail.data == node_3_data
    assert linked_list.tail.next_node is None
    assert linked_list.tail.previous_node is not None
    assert linked_list.tail.previous_node.data == node_2_data

    middle_node = linked_list.head.next_node
    assert middle_node.data == node_2_data
    assert middle_node.next_node is not None
    assert middle_node.next_node.data is not None
    assert middle_node.next_node.data == node_3_data
    assert middle_node.previous_node is not None
    assert middle_node.previous_node.data is not None
    assert middle_node.previous_node.data == node_1_data
Ejemplo n.º 52
0
from linked_list import LinkedList
from pprint import pprint

list = LinkedList()
list.append(3)
list.append('b')
list.append('v')
list.append(list)
list.append(0)
print(list.__unicode__())
Ejemplo n.º 53
0
class TestLinkedList(unittest.TestCase):

    def setUp(self):
        self.list = LinkedList()


    def tearDown(self):
        self.list = None


    def test_append(self):
        self.list.append("Mr. Green")

        self.assertTrue(self.list.head.data == "Mr. Green")
        self.assertTrue(self.list.head.next_node is None)


    def test_append_two(self):
        self.list.append("Mr. Green")
        self.list.append("Miss Scarlet")

        self.assertTrue(self.list.head.data == "Miss Scarlet")

        new_head = self.list.head.next_node
        self.assertTrue(new_head.data == "Mr. Green")


    def test_next_node(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        self.assertTrue(self.list.head.data == "Mr. Boddy")

        new_head = self.list.head.next_node
        self.assertTrue(new_head.data == "Mrs. Peacock")

        last = new_head.next_node
        self.assertTrue(last.data == "Prof. Plum")


    def test_len(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        length = self.list.__len__()

        self.assertTrue(length == 3)


    def test_len_zero(self):
        length = self.list.__len__()

        self.assertTrue(length == 0)


    def test_len_one(self):
        self.list.append("Prof. Plum")
        length = self.list.__len__()

        self.assertTrue(length == 1)


    def test_succeed_getitem(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        result = self.list.__getitem__(0)
        self.assertTrue(result == "Mr. Boddy")

        result = self.list.__getitem__(1)
        self.assertTrue(result == "Mrs. Peacock")

        result = self.list.__getitem__(2)
        self.assertTrue(result == "Prof. Plum")


    def test_fail_getitem(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")

        with self.assertRaises(IndexError):
            self.list.__getitem__(2)


    @unittest.skip('Extra Challenge: pop method.')
    def test_pop(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        old_head = self.list.pop()
        self.assertTrue(old_head.data == "Mr. Boddy")

        new_head = self.list.head
        self.assertTrue(new_head.data == "Mrs. Peacock")

        new_length = len(self.list)
        self.assertTrue(new_length == 2)


    @unittest.skip('Extra Challenge: pop method.')
    def test_pop_empty_list(self):
        with self.assertRaises(IndexError):
            self.list.pop()


    @unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        # Delete the list head
        self.list.__delitem__(0)
        self.assertTrue(self.list.head.data == "Mrs. Peacock")

        # Delete the list tail
        self.list.__delitem__(1)
        self.assertTrue(self.list.head.next_node is None)

        new_length = len(self.list)
        self.assertTrue(new_length == 1)


    @unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete_value_not_in_list(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        with self.assertRaises(IndexError):
            self.list.__delitem__(3)


    @unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete_empty_list(self):
        with self.assertRaises(IndexError):
            self.list.__delitem__(1)


    @unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete_next_reassignment(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. White")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        self.list.__delitem__(1)
        self.list.__delitem__(1)

        self.assertTrue(self.list.head.next_node.data == "Prof. Plum")
Ejemplo n.º 54
0
def test_flip() -> None:
    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    node_4_data = {"id": 4}
    node_5_data = {"id": 5}
    linked_list = LinkedList()
    linked_list.append(node_1_data)
    linked_list.append(node_2_data)
    linked_list.append(node_3_data)
    linked_list.append(node_4_data)
    linked_list.append(node_5_data)

    # non-consecutive nodes:
    # 1 2 3 4 5 -> 1 4 3 2 5
    linked_list.flip(linked_list.head.next_node, linked_list.tail.previous_node, "id")

    first_node = linked_list.head
    assert first_node.data == node_1_data
    assert first_node.previous_node is None
    assert first_node.next_node.data == node_4_data
    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_4_data
    assert second_node.previous_node.data == node_1_data
    assert second_node.next_node.data == node_3_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_3_data
    assert third_node.previous_node.data == node_4_data
    assert third_node.next_node.data == node_2_data
    fourth_node = third_node.next_node
    assert fourth_node is not None
    assert fourth_node.data == node_2_data
    assert fourth_node.previous_node.data == node_3_data
    assert fourth_node.next_node.data == node_5_data
    fifth_node = fourth_node.next_node
    assert fifth_node is not None
    assert fifth_node.data == node_5_data
    assert fifth_node.previous_node.data == node_2_data
    assert fifth_node.next_node is None
    assert linked_list.tail.data == node_5_data

    # consecutive nodes:
    # 1 4 3 2 5 -> 1 4 2 3 5
    linked_list.flip(linked_list.tail.previous_node.previous_node, linked_list.tail.previous_node, "id")

    first_node = linked_list.head
    assert first_node.data == node_1_data
    assert first_node.previous_node is None
    assert first_node.next_node.data == node_4_data
    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_4_data
    assert second_node.previous_node.data == node_1_data
    assert second_node.next_node.data == node_2_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_2_data
    assert third_node.previous_node.data == node_4_data
    assert third_node.next_node.data == node_3_data
    fourth_node = third_node.next_node
    assert fourth_node is not None
    assert fourth_node.data == node_3_data
    assert fourth_node.previous_node.data == node_2_data
    assert fourth_node.next_node.data == node_5_data
    fifth_node = fourth_node.next_node
    assert fifth_node is not None
    assert fifth_node.data == node_5_data
    assert fifth_node.previous_node.data == node_3_data
    assert fifth_node.next_node is None
    assert linked_list.tail.data == node_5_data

    # A = head B = tail
    # 1 4 3 2 5 -> 5 4 2 3 1
    linked_list.flip(linked_list.head, linked_list.tail, "id")

    first_node = linked_list.head
    assert first_node.data == node_5_data
    assert first_node.previous_node is None
    assert first_node.next_node.data == node_4_data
    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_4_data
    assert second_node.previous_node.data == node_5_data
    assert second_node.next_node.data == node_2_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_2_data
    assert third_node.previous_node.data == node_4_data
    assert third_node.next_node.data == node_3_data
    fourth_node = third_node.next_node
    assert fourth_node is not None
    assert fourth_node.data == node_3_data
    assert fourth_node.previous_node.data == node_2_data
    assert fourth_node.next_node.data == node_1_data
    fifth_node = fourth_node.next_node
    assert fifth_node is not None
    assert fifth_node.data == node_1_data
    assert fifth_node.previous_node.data == node_3_data
    assert fifth_node.next_node is None
    assert linked_list.tail.data == node_1_data
Ejemplo n.º 55
0
def test_sorting() -> None:

    def node_comparison_function(node):
        return int(node.data["id"]) if node else 0

    node_1_data = {"id": 1}
    node_2_data = {"id": 2}
    node_3_data = {"id": 3}
    node_4_data = {"id": 4}

    linked_list = LinkedList()
    linked_list.append(node_4_data)
    linked_list.append(node_3_data)
    linked_list.append(node_2_data)
    linked_list.append(node_1_data)

    # 4 3 2 1 -> 1 2 3 4
    linked_list.sort(comparison_function=node_comparison_function)

    first_node = linked_list.head
    assert first_node.data == node_1_data
    assert first_node.previous_node is None
    assert first_node.next_node.data == node_2_data
    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_2_data
    assert second_node.previous_node.data == node_1_data
    assert second_node.next_node.data == node_3_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_3_data
    assert third_node.previous_node.data == node_2_data
    assert third_node.next_node.data == node_4_data
    fourth_node = third_node.next_node
    assert fourth_node is not None
    assert fourth_node.data == node_4_data
    assert fourth_node.previous_node.data == node_3_data
    assert fourth_node.next_node is None
    assert linked_list.tail.data == node_4_data

    linked_list = LinkedList()
    linked_list.append(node_1_data)
    linked_list.append(node_2_data)
    linked_list.append(node_3_data)
    linked_list.append(node_4_data)

    # 1 2 3 4 -> 4 3 2 1
    linked_list.sort(comparison_function=node_comparison_function, reverse=True)

    first_node = linked_list.head
    assert first_node.data == node_4_data
    assert first_node.previous_node is None
    assert first_node.next_node.data == node_3_data
    second_node = linked_list.head.next_node
    assert second_node is not None
    assert second_node.data == node_3_data
    assert second_node.previous_node.data == node_4_data
    assert second_node.next_node.data == node_2_data
    third_node = second_node.next_node
    assert third_node is not None
    assert third_node.data == node_2_data
    assert third_node.previous_node.data == node_3_data
    assert third_node.next_node.data == node_1_data
    fourth_node = third_node.next_node
    assert fourth_node is not None
    assert fourth_node.data == node_1_data
    assert fourth_node.previous_node.data == node_2_data
    assert fourth_node.next_node is None
    assert linked_list.tail.data == node_1_data
Ejemplo n.º 56
0
class TestLinkedList(unittest.TestCase):

	def setUp(self):
		self.emptyList = LinkedList()
		self.oneItemList = LinkedList()
		self.twoItemList = LinkedList()
		self.fiveItemList = LinkedList()

		self.one = [3]
		self.two = [2, 9]
		self.five = [6, 1, 0, 5, 8]

		for i in self.one:
			self.oneItemList.append(i)

		for i in self.two:
			self.twoItemList.append(i)

		for i in self.five:
			self.fiveItemList.append(i)

	def testEmptyAppend(self):
		self.emptyList.append(4)
		self.assertEqual(self.emptyList.getPosition(0), 4)

	def testOneAppend(self):
		self.oneItemList.append(1)
		self.assertEqual(self.oneItemList.getPosition(0), 3)
		self.assertEqual(self.oneItemList.getPosition(1), 1)

	def testTwoAppend(self):
		self.twoItemList.append(6)
		self.assertEqual(self.twoItemList.getPosition(0), 2)
		self.assertEqual(self.twoItemList.getPosition(1), 9)
		self.assertEqual(self.twoItemList.getPosition(2), 6)

	def testEmptyPrepend(self):
		self.emptyList.prepend(4)
		self.assertEqual(self.emptyList.getPosition(0), 4)

	def testOnePrepend(self):
		self.oneItemList.prepend(1)
		self.assertEqual(self.oneItemList.getPosition(0), 1)

	def testTwoPrepend(self):
		self.twoItemList.prepend(6)
		self.assertEqual(self.twoItemList.getPosition(0), 6)
		self.assertEqual(self.twoItemList.getPosition(1), 2)
		self.assertEqual(self.twoItemList.getPosition(2), 9)

	def testEmptyInsertAfter(self):
		self.assertFalse(self.emptyList.insertAfter(1, 3))

	def testOneInsertAfter(self):
		self.assertTrue(self.oneItemList.insertAfter(2, 0))
		self.assertEqual(self.oneItemList.getPosition(1), 2)
		self.assertFalse(self.oneItemList.find(7))

	def testTwoInsertAfter(self):
		self.assertTrue(self.twoItemList.insertAfter(7, 0))
		self.assertEqual(self.twoItemList.getPosition(1), 7)
		self.assertFalse(self.twoItemList.find(3))

	def testEmptyRemoveBeginning(self):
		self.assertFalse(self.emptyList.removeBeginning())

	def testOneRemoveBeginning(self):
		self.assertTrue(self.oneItemList.removeBeginning())
		self.assertFalse(self.oneItemList.getPosition(0))

	def testTwoRemoveBeginning(self):
		self.assertTrue(self.twoItemList.removeBeginning())
		self.assertEqual(self.twoItemList.getPosition(0), 9)

	def testEmptyRemoveAfter(self):
		self.assertFalse(self.emptyList.removeAfter(0))

	def testOneRemoveAfter(self):
		self.assertFalse(self.oneItemList.removeAfter(0))

	def testTwoRemoveAfter(self):
		self.assertTrue(self.twoItemList.removeAfter(0))

	def testEmptyFind(self):
		self.assertFalse(self.emptyList.find(0))

	def testOneFind(self):
		self.assertFalse(self.oneItemList.find(0))
		self.assertTrue(self.oneItemList.find(3))

	def testTwoFind(self):
		self.assertTrue(self.fiveItemList.find(8))
		self.assertFalse(self.fiveItemList.find(3))

	def testFiveFind(self):
		self.assertTrue(self.fiveItemList.find(0))
		self.assertFalse(self.fiveItemList.find(2))
Ejemplo n.º 57
0
class LinkedListTestCase(unittest.TestCase):
    def setUp(self):
        self.headValue = 1
        self.nValue = 2
        self.nnValue = 3
        self.l = LinkedList(self.headValue)

    def test_property(self):
        n = Node()
        n.value = 1
        self.assertEqual(n.value, 1, "Property test") 

    def test_linked_list_head_exist(self):
        self.assertTrue(isinstance(self.l.head, Node))

    def test_linked_list_append_next(self):
        self.l.append(self.nValue)
        self.assertEqual(self.l.head._next.value, self.nValue, "append node next")

    def test_linked_list_append_prev(self):
        self.l.append(self.nValue)
        self.assertEqual(self.l.head._next.prev.value, self.l.head.value, "append node prev")

    def test_linked_list_many_time_append_next(self):
        self.l.append(self.nValue)
        self.l.append(self.nnValue)
        self.assertEqual(self.l.head._next.value, self.nValue, "append many time next")

    def test_linked_list_many_time_append_prev(self):
        self.l.append(self.nValue)
        self.l.append(self.nnValue)
        self.assertEqual(self.l.head._next._next.prev.value, self.nValue, "append many time prev")

    def test_call(self):
        self.l.append(self.nValue)
        self.l.append(self.nnValue)
        self.assertEqual(self.l.call(2).value, self.nnValue, "check call(2)")
        self.assertEqual(self.l.call(1).value, self.nValue, "check call(1)")
        self.assertEqual(self.l.call(0).value, self.headValue, "check call(0)")

    def test_delete(self):
        self.l.append(self.nValue)
        self.l.append(self.nnValue)
        self.l.delete(1)
        self.assertEqual(self.l.head._next.value, self.nnValue, "check delete function next")
        self.assertEqual(self.l.head._next.prev.value, self.headValue, "check delete function prev")
    '''
Ejemplo n.º 58
0
"""

from linked_list import LinkedList

def delete_mid_node(middle_node):
    if middle_node is None:
        return 0

    if middle_node.next is not None:
        middle_node.value = middle_node.next.value
        middle_node.next = middle_node.next.next
        middle_node.next.next = None

    return middle_node


linked_list = LinkedList()
letters = ['a', 'b', 'c', 'd', 'e']

for let in letters:
    linked_list.append(let)

print(str(linked_list))

mid_node = linked_list.get_node('c')
print(str(mid_node))

print(str(delete_mid_node(mid_node)))
print(str(linked_list))