def test_get_next():
    """Test node module get next method."""
    from linked_list import Node
    test_node1 = Node(data[0])
    test_node2 = Node(data[1])
    test_node1.set_next(test_node2)
    assert test_node1.get_next() == test_node2
Example #2
0
def list_to_tree(l):
    if not l:  return None
    mid = (len(l)-1)/2
    n = Node(l[mid])
    n.left = list_to_tree(l[:mid])
    n.right = list_to_tree(l[(mid+1):])
    return n
Example #3
0
 def recurse(l,left,right):
     if left > right: return None
     mid = (left+right)/2
     n = Node(l[mid])
     n.left = recurse(l,left,mid-1)
     n.right = recurse(l,mid+1,right)
     return n
Example #4
0
 def push(self, elem):
   node = Node(elem)
   if not self.tail:
     self.tail = node
   self.tail.next = node
   node.prev = self.tail
   self.tail = node
Example #5
0
    def insert(self, item_new, pos):
        """given an item and a position, this method insert an item at the position required"""

        actual_position = 0
        previous_position = None
        current = self.head
        new_node = Node(None, item_new)

        while actual_position != pos and current is not None:
            previous_position = current
            current = current.next
            actual_position += 1

        if actual_position != pos:
            raise ValueError("Invalid Position %d" % pos)

        previous_position.next = new_node
        new_node.next = current
        new_node.previous = previous_position

        if current is None:
            self.tail = new_node
        else:
            current.previous = new_node

        return self
 def testNext(self):
     node = Node(data="data",next=None)
     first_node = Node(data="first",next=node)
     self.assertEqual(first_node.next,node)
     third = Node(data="third",next=None)
     node.next = third
     self.assertEqual(node.next,third)
Example #7
0
 def insert_after(self, index, value):
     node = self.get_node_by_index(index)
     newnode = Node(value)
     newnode.next = node.next
     node.next = newnode
     if newnode.next == None:
         self.tail_node = newnode
     self.list_length += 1
Example #8
0
 def double(node):
     if not node: return
     n = Node(node.val)
     old_left = node.left
     n.left = old_left
     node.left = n
     double(old_left)
     double(node.right)
Example #9
0
def add_forward(node1, node2):
    if not node1 and not node2:
        return (None, 0)
    next, carry = add_forward(node1.next, node2.next)
    q, r = divmod(node1.value + node2.value + carry, 10)
    node = Node(r)
    node.next = next
    return (node, q)
Example #10
0
def list_to_tree_parent(l):
    if not l:  return None
    mid = (len(l)-1)/2
    n = Node(l[mid])
    n.parent = None
    n.left = list_to_tree_parent(l[:mid])
    if n.left: n.left.parent = n
    n.right = list_to_tree_parent(l[(mid+1):])
    if n.right: n.right.parent = n
    return n
Example #11
0
	def __init__(self, key, value):
		"""
		Initializes new HTNode

		Arguments:
			data = key for an associated values
			value = value to be stored associated with the key 
		"""
		Node.__init__(self,key)
		self.value = value
Example #12
0
 def insert_before(self, index, value):
     newnode = Node(value)
     if index == 0:
         newnode.next = self.head_node
         if self.head_node == None:  # insert_before(0,*) should still work on an empty list
             self.tail_node = newnode
         self.head_node = newnode
     else:
         node = self.get_node_by_index(index - 1)
         newnode.next = node.next
         node.next = newnode
     self.list_length += 1
Example #13
0
 def append(self, value):
     """Append a value to the end of a double link list."""
     current_node = self.head
     if current_node is not None:
         while current_node.next_node is not None:
             current_node = current_node.next_node
         new_node = Node(value)
         current_node.next_node = new_node
         new_node.prev = current_node
     else:
         new_node = Node(value)
         current_node = new_node
         self.head = current_node
Example #14
0
def add_reversed(node1, node2, carry):
    if not node1 and not node2 and carry == 0:
        return
    sum = carry
    if node1:
        sum += node1.value
    if node2:
        sum += node2.value
    q, r = divmod(sum, 10)
    node = Node(r)
    node.next = add_reversed(node1.next if node1 else None,
                             node2.next if node2 else None,
                             q)
    return node
Example #15
0
def solution2(head1, head2):
    # If linked lists have different lengths, pad with 0s
    len1, len2 = length(head1), length(head2)
    if len1 < len2:
        head1 = pad_with_zeros(head1, len2-len1)
    elif len1 > len2:
        head2 = pad_with_zeros(head2, len1-len2)

    # Now that the linked lists are of equal size, add them
    head, carry = add_forward(head1, head2)
    if carry != 0:
        node = Node(carry)
        node.next, head = head, node  # insert at front

    return head
def sum(n1, n2):
	carry = 0
	sum = Node(None)
	while n1 is not None or n2 is not None:
		cur_sum = carry
		if n1 is not None:
			cur_sum += n1.value
			n1 = n1.next
		if n2 is not None:
			cur_sum += n2.value
			n2 = n2.next
		carry = cur_sum / 10
		sum.add_to_tail(cur_sum % 10)
	if carry > 0:
		sum.add_to_tail(carry)
	return sum.next
Example #17
0
def ll_add_rev(n1,n2,rem):
    if not n1 and not n2 and not rem:
        return None

    val = rem
    if n1:
        val += n1.val
    if n2:
        val += n2.val

    rem = 0

    n = Node(val % 10)

    new_node = ll_add_rev(n1.nxt if n1 else None,
                          n2.nxt if n2 else None,
                          1 if val > 9 else 0)

    n.nxt = new_node

    return n
Example #18
0
 def insert(self, value):
     """Insert a value onto the double linked list."""
     try:
         for i in value:
             new_node_value = Node(i)
             if self.head is None:
                 self.head = new_node_value
                 self.length += 1
             else:
                 new_node_value.next_node = self.head
                 new_node_value.next_node.prev = new_node_value
                 self.head = new_node_value
                 self.length += 1
     except TypeError:
         new_node_value = Node(value)
         if self.head is None:
             self.head = new_node_value
             self.length += 1
         else:
             new_node_value.next_node = self.head
             new_node_value.next_node.prev = new_node_value
             self.head = new_node_value
             self.length += 1
Example #19
0
 def test_init(self):
     data = 'ABC'
     node = Node(data)
     # Initializer should add instance properties
     assert node.data is data
     assert node.next is None
def test_get_data():
    """Test node module get data method."""
    from linked_list import Node
    test_node = Node(data[0])
    assert test_node.get_data() == data[0]
def test_set_next():
    """Test get_next method."""
    from linked_list import Node
    new_node = Node("word", "chimichanga")
    new_node.set_next("next")
    assert new_node.get_next() == "next"
def test_get_data():
    """Test get_data method."""
    from linked_list import Node
    new_node = Node("word")
    assert new_node.get_data() == "word"
 def test_node_str_representation_with_next(self):
     n = Node(9)
     n.next = Node('X')
     self.assertEqual(str(n), "Node(9) > Node(X)")
def insert_at_beginning(head, data):
    temp = head
    node_to_insert = Node(data)
    node_to_insert.next = temp
    return node_to_insert
Example #25
0
    slow = l
    fast = l.next
    if fast is None:
        return

    while fast is not slow:
        # No cycle
        if fast.next is None or fast.next.next is None:
            return
        fast = fast.next.next
        slow = slow.next

    slow = l
    fast = fast.next

    while fast is not slow:
        slow = slow.next
        fast = fast.next

    return slow


# Create linked list with cycle
l = Node.from_iterable([1, 2, 3, 4, 5])
c = Node.from_iterable([6, 7, 8, 9, 10, 11])
l.last.next = c
c.last.next = c

st = cycle_start(l)
print(st.val if st is not None else 'No cycle')
            return True

    def __str__(self):
        if self.isEmpty():
            return 'Queue is empty.'

        else:
            queue = ['->[Front]']

            current = self.first
            while current:
                queue.insert(-1, f'->{current.value}')
                current = current.next
            queue.insert(0, '[Rear]')
            return ''.join(queue)


queue = Queue()

e1 = Node(4)
e2 = Node(5)
e3 = Node(6)

queue.Enqueue(e1)
queue.Enqueue(e2)
queue.Enqueue(e3)
# print(queue.Dequeue().value)
print(queue)
queue.reverse()
print(queue)
Example #27
0
def test_node_init():
    """Test node class init."""
    from linked_list import Node
    new_node = Node(0, None)
    assert new_node.contents == 0 and new_node.next_node is None
Example #28
0
def create_nodes():
    """ Creates 3 nodes to use for testing, returns a 3 element tuple """
    n1 = Node(1)
    n2 = Node(2)
    n3 = Node(3)
    return n1, n2, n3
Example #29
0
def test_node_creation():
    n1 = Node(1)
    assert n1.value == 1
    assert n1.next == None
Example #30
0
 def push(self,val):
     n = Node(val)
     n.nxt = self.top
     self.top = n
     if not self.minstack.peek() or val < self.minstack.peek():
         self.minstack.push(val)
Example #31
0
 def test_init(self):
     data = 'ABC'
     node = Node(data)
     assert node.data is data
     assert node.next is None
def insert_before(node, value):
    new_node = Node(value)
    new_node.next = node
    return new_node
Example #33
0
 def push(self, item):
     node = Node(item)
     node.link = self.top
     self.top = node
Example #34
0
from linked_list import LinkedList, Node

def show_all(ll):
  ll.reset()
  for i in range(0,ll.size):
    n = ll.current
    print "position %d element %s" % (i, str(n.e))
    ll.next_()

ll = LinkedList()
ll.add_e('q')
ll.add_e('w')
ll.add_e('e')
ll.add_e('r')
ll.add_e('t')

node = Node('y')
ll.add_node(node)

show_all(ll)

Example #35
0
def test_next_node_none():
    bob = Node("Bob")
    newList = LinkedList()
    newList.insert(bob)
    assert newList.firstNode.nextNode is None
Example #36
0
def test_instance_of_node():
    assert Node('Node_1').value == 'Node_1'
def test_get_next():
    """Test get_next method."""
    from linked_list import Node
    new_node = Node("word", "next")
    assert new_node.get_next() == "next"
Example #38
0
def test_one_item_in_list(list_one):
    assert list_one.head and Node('Node_1').next_node == None
def test_set_data():
    """Test node module set data method."""
    from linked_list import Node
    test_node = Node(data[0])
    test_node.set_data(data[1])
    assert test_node.data == data[1]
Example #40
0
def node():
    return Node(42)
    node = l
    prev = None

    for _ in range(m):
        prev = node
        node = node.next

    head_tail = prev
    rev_tail = node

    for _ in range(n - m + 1):
        if not node:
            break
        next = node.next
        node.next = prev
        prev = node
        node = next

    rev_head = prev
    tail_head = node

    if head_tail is not None:
        head_tail.next = rev_head
    rev_tail.next = tail_head

    return l if m else rev_head


l = Node.from_iterable([1, 2, 3, 4, 5, 6, 7, 8])
print(reverse(l, 2, 4))
def test_make_node():
    expected = Node
    actual = Node(3)
    assert type(actual) == expected
from linked_list import Node

node = Node()
node.insert_at_beginning(5)
node.insert_at_beginning(4)
node.insert_at_beginning(2)
node.insert_at_beginning(1)


def insert_in_sorted_list(node, item):
    previous = None
    current = node.head
    stop = False

    while current != None and not stop:
        if current.data > item:
            stop = True
        else:
            previous = current
            current = current.next

    temp = Node(item)
    if previous == None:
        temp.next = node.head
        node.head = temp
    else:
        temp.next = current
        previous.next = temp


insert_in_sorted_list(node, 3)
Example #44
0
 def test(self):
     n1 = Node('hello')
     n2 = Node('world')
     n1.next = n2
     self.assertTrue(n1.next.val == 'world')
 def test_node_equal_value_different_next_node(self):
     self.assertNotEqual(Node(1, next=Node('next1')),
                         Node(1, next=Node('next2')))
     self.assertNotEqual(Node('hello', next=Node('next1')),
                         Node('hello', next=Node('next2')))
     self.assertNotEqual(Node(True, next=Node('next1')),
                         Node(True, next=Node('next2')))
     self.assertNotEqual(Node([1, 2, 3], next=Node('next1')),
                         Node([1, 2, 3], next=Node('next2')))
 def test_node_equal_value(self):
     self.assertEqual(Node(1), Node(1))
     self.assertEqual(Node('hello'), Node('hello'))
     self.assertEqual(Node(True), Node(True))
     self.assertEqual(Node([1, 2, 3]), Node([1, 2, 3]))
 def test_node_str_representation_without_next(self):
     self.assertEqual(str(Node(9)), "Node(9) > /")
Example #48
0
def test_node_data():
    newNode = Node("Bob")
    assert newNode.data == "Bob"
 def test_node_not_equal_value(self):
     self.assertNotEqual(Node(1), Node(2))
     self.assertNotEqual(Node('hello'), Node('bye'))
     self.assertNotEqual(Node(True), Node(False))
     self.assertNotEqual(Node([1, 2, 3]), Node([3, 2, 1]))
Example #50
0
 def push(self, num):
     """Stack's push operation."""
     newNode = Node(num)
     newNode.next = self.top if self.top.val else None
     self.top = newNode
Example #51
0
 def test_property(self):
     n = Node()
     n.value = 1
     self.assertEqual(n.value, 1, "Property test") 
Example #52
0
For example,

List 1-->2-->1 is a palindrome.
List 1-->2-->3 is not a palindrome.
"""

from __future__ import print_function
from linked_list import Node


def is_palindrome(l):
    n = len(l)
    head, tail = l.split(n//2 - 1)
    head = head.reverse()
    if n % 2:
        result = head==tail.next
    else:
        result = head==tail
    head = head.reverse()
    head.join(tail)
    return result


for l in (
    Node.from_iterable([1, 2, 3, 2, 1]),
    Node.from_iterable([1, 2, 3, 2, 3]),
    Node.from_iterable([1, 2, 3, 3, 2, 1]),
    Node.from_iterable([1, 2, 3, 3, 2, 3])
):
    print(is_palindrome(l), l)
Example #53
0
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
"""

from __future__ import print_function
from linked_list import Node


def partition(l, x):
    heads = [None, None]
    tails = [None, None]

    while l:
        ind = int(l.val >= x)
        if heads[ind] is None:
            heads[ind] = l
        if tails[ind] is not None:
            tails[ind].next = l
        tails[ind] = l
        l = l.next
        tails[ind].next = None

    if tails[0]:
        tails[0].next = heads[1]
    return heads[0] or heads[1]


l = Node.from_iterable([1, 4, 3, 2, 5, 2])
print(partition(l, 3))
Example #54
0
def reverse(n1):
	prev= None
	current = n1
	while current!=None:
		right = current.next
		current.next = prev
		prev = current
		current = right
	return prev
	
def printList(n):
	while n!= None:
		print n.value
		n = n.next

n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)

n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = None

printList(n1)
nret = reverse(n1)
print nret.value
printList(nret)
Example #55
0
    if length == 1:
        return node.next
    if length == 2:
        if node.value == node.next.value:
            return node.next.next
        else:
            return -1
    last_node = visit(node.next, length-2)
    if last_node != -1:
        if node.value == last_node.value:
            return last_node.next
    return -1


def palindrome(head):
    length = 0
    node = head
    while node:
        length += 1
        node = node.next
    print visit(head, length)


head = Node('r')
head.next = Node('a')
head.next.next = Node('d')
head.next.next.next = Node('a')
head.next.next.next.next = Node('r')

palindrome(head)  # None if palindrome, -1 otherwise
 def __init__(self, value, previous, next):
     self.previous = previous
     Node.__init__(self, value, next)
Example #57
0
from linked_list import Node

# head1 = Node(None)
lst_node1 = Node(2)
node_2 = Node(4)
node_3 = Node(3)
# tail = Node(None)
# head1.next = node_1
lst_node1.next = node_2
node_2.next = node_3
# node_3.next = tail

# head2 = Node(None)
lst_node2 = Node(5)
node_2 = Node(6)
node_3 = Node(4)
# tail = Node(None)
# head2.next = node_1
lst_node2.next = node_2
node_2.next = node_3

# node_3.next = tail


# my
def sum_twolist(l1, l2):
    lst1, lst2 = [], []

    while l1:
        value = l1.data
        lst1.append(value)
Example #58
0
def test_node_add():
    bob = Node("Bob")
    newList = LinkedList()
    newList.insert(bob)
    assert newList.firstNode.data == "Bob"
Example #59
0
__author__ = 'idmrga'
from linked_list import Node
from linked_list import UnorderedList

temp = Node(34)
print(temp.getData())

l = UnorderedList()
l.add(5)
print l.search(5)


Example #60
0
 def __init__(self):
     """A Linked List Prototype."""
     self.top = Node()