예제 #1
0
def alternateSegregate(l):
    if l.head is None:
        return
    first, second = LinkedList(), LinkedList()
    lastNode = l.head
    while lastNode.next:
        lastNode = lastNode.next
    current = l.head
    lNode = lastNode
    prev = None
    while current != lastNode:
        next = current.next
        current.next = next.next
        lNode.next = next
        next.next = None
        lNode = lNode.next
        prev = current
        current = current.next
        if lNode == lastNode:
            break
    first.head = l.head
    second.head = current if lastNode == lNode else current.next
    if lastNode != lNode:
        current.next = None
    else:
        print current.data
        prev.next = None
    return [first, second]
예제 #2
0
def mergeKSortedLists(lists):
    while len(lists) > 1:
        p, q = lists.pop(0), lists.pop(0)
        lists.append(merge(p, q))
    l = LinkedList()
    l.head = lists[0]
    return l
def intersectionOfSortedLists(a, b):
    result = LinkedList()
    while a and b:
        if a.data == b.data:
            result.append(a.data)
            a, b = a.next, b.next
        elif a.data > b.data:
            b = b.next
        else:
            a = a.next
    return result
    def test_clean(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n1)
        linked_list.add_in_tail(self.n2)
        linked_list.add_in_tail(self.n3)
        linked_list.clean()

        self.assertEqual(linked_list.len(), 0)
    def test_find_all_5(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n1)
        linked_list.add_in_tail(self.n2)
        linked_list.add_in_tail(self.n3)
        linked_list.add_in_tail(self.n4)
        linked_list.add_in_tail(self.n5)

        self.assertEqual(linked_list.find_all(12), [self.n1, self.n2, self.n4, self.n5])
    def test_delete_all_2(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n1)
        linked_list.add_in_tail(self.n3)
        linked_list.add_in_tail(self.n2)

        linked_list.delete(12, True)
        self.assertEqual(linked_list.head, self.n3)
        self.assertEqual(linked_list.tail, self.n3)
    def test_delete_8(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n1)
        linked_list.add_in_tail(self.n2)
        linked_list.add_in_tail(self.n4)

        linked_list.delete(12)
        self.assertEqual(linked_list.head, self.n2)
        self.assertEqual(linked_list.tail, self.n4)
    def test_insert_2(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n1)
        linked_list.add_in_tail(self.n2)
        linked_list.add_in_tail(self.n3)

        linked_list.insert(self.n3, self.n4)

        self.assertEqual(self.n3.next, self.n4)
        self.assertEqual(linked_list.tail, self.n4)
    def test_insert_3(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n1)
        linked_list.add_in_tail(self.n2)
        linked_list.add_in_tail(self.n3)

        linked_list.insert(self.n2, self.n6)

        self.assertEqual(self.n2.next, self.n6)
        self.assertEqual(self.n6.next, self.n3)
    def test_len_3_elements(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n1)
        linked_list.add_in_tail(self.n2)
        linked_list.add_in_tail(self.n3)

        self.assertEqual(linked_list.len(), 3)
예제 #11
0
def sort(l):
    a = LinkedList()
    node = l.head
    while node:
        temp = node.next
        node.next = None
        sortedInsert(a, node)
        node = temp
    l.head = a.head
    def test_delete_4(self):
        linked_list = LinkedList()
        linked_list.add_in_tail(self.n3)
        linked_list.add_in_tail(self.n4)
        linked_list.add_in_tail(self.n6)
        
        linked_list.delete(12)

        self.assertEqual(linked_list.head, self.n3)
        self.assertEqual(self.n3.next, self.n6)
        self.assertEqual(linked_list.tail, self.n6)
def initialize():
    head = Node(-1)
    linked = LinkedList(head)

    # Create continuous node to head
    for i in range(0, 5):
        linked.add_end(i)

    # Printing out the result
    print("Print Linked List Iterate Result")
    # expected to show) -1, 0, 1, 2, 3, 4
    linked.to_string()

    return head, linked
def load_network(graph, network):
    """
    Loads a network from a given file or object(if saved earlier)
    :param graph: Graph Object
    :param network: network file
    :return: None
    """
    network = open(network, "r")  # open given file
    for line in network:  # iterate over whole file line by line
        line = line.rstrip().lstrip(
        )  # removes any white spaces after or before the node value
        if ':' not in line:  # if line has node to add
            graph.list.add_last(LinkedList(line))  # add node to the grpah
        else:  # if line has nodes to connect
            vertices = line.split(
                ':'
            )  # makes list of two nodes by spliting the line on delimiter
            vertices[0] = vertices[0].rstrip().lstrip()  #
            vertices[1] = vertices[1].rstrip().lstrip()
            graph.connect(vertices[0],
                          vertices[1])  # make a connection between node
    network.close()  # close the open file
예제 #15
0
파일: stack.py 프로젝트: heliy/algorithms
class ListStack(object):
    '''
    Pushdown Stack(linked-list implmentation).
    -------------
      Stack(): init queue
      push(item): push an item
      pop(): remove the most recently added item
      top(): get the most recently added item
      empty = isEmpty(): tell stack is empty
      stackSize = size(): get size of stack 
      clear(): reset the stack
    
    '''
    def __init__(self):
        self.list = LinkedList()

    def push(self, item):
        self.list.addHead(item)

    def isEmpty(self):
        return self.list.isEmpty()

    def pop(self):
        if self.isEmpty():
            return
        self.list.remove(0)

    def top(self):
        if self.isEmpty():
            return None
        return self.list.get(0).item

    def size(self):
        return self.list.size()

    def clear(self):
        self.list = LinkedList()
예제 #16
0
def add(a, b):
    result = LinkedList()
    lastNode = None
    carry = 0
    while a and b:
        sum = a.data + b.data + carry
        if lastNode:
            lastNode.next = Node(sum % 10)
            lastNode = lastNode.next
        else:
            result.head = Node(sum % 10)
            lastNode = result.head
        carry = sum / 10
        a, b = a.next, b.next
    while a:
        sum = a.data + carry
        if lastNode:
            lastNode.next = Node(sum % 10)
            lastNode = lastNode.next
        else:
            result.head = Node(sum % 10)
            lastNode = result.head
        carry = sum / 10
        a = a.next
    while b:
        sum = b.data + carry
        if lastNode:
            lastNode.next = Node(sum % 10)
            lastNode = lastNode.next
        else:
            result.head = Node(sum % 10)
            lastNode = result.head
        carry = sum / 10
        b = b.next
    if carry == 1:
        if lastNode:
            lastNode.next = Node(1)
        else:
            result.head = Node(1)
    return result
def merge(a, b):
    l = LinkedList()
    while a and b:
        if a.data <= b.data:
            temp = a.next
            a.next = l.head
            l.head = a
            a = temp
        else:
            temp = b.next
            b.next = l.head
            l.head = b
            b = temp
    while a:
        temp = a.next
        a.next = l.head
        l.head = a
        a = temp
    while b:
        temp = b.next
        b.next = l.head
        l.head = b
        b = temp
    return l
예제 #18
0
def add(a, b):
    l1 = a.size()
    l2 = b.size()
    p = a.head if l1 > l2 else b.head
    q = a.head if l1 <= l2 else b.head
    d = abs(l1 - l2)
    s = []
    while d > 0:
        s.append([p.data, 0])
        p = p.next
        d -= 1
    while p and q:
        s.append([(p.data + q.data) % 10, (p.data + q.data) / 10])
        p = p.next
        q = q.next
    l = LinkedList()
    carry = 0
    while len(s) > 0:
        node = s.pop()
        l.push((node[0] + carry) % 10)
        carry = node[1] + (node[0] + carry) / 10
    if carry > 0:
        l.push(carry)
    return l
        if (a.data > b.data):
            a.data, b.data = b.data, a.data
            temp = b
            while b.next and b.data > b.next.data:
                b = b.next
                prev, ptr = None, b
                while ptr and ptr.data < temp.data:
                    prev, ptr = ptr, ptr.next
                prev.next = temp
                temp.next = ptr
        if a.next is None:
            break
        a = a.next
    while a.next:
        a = a.next
    a.next = b

a = LinkedList()
a.append(2)
a.append(4)
a.append(7)
a.append(8)
a.append(10)

b = LinkedList()
b.append(1)
b.append(3)
b.append(12)

merge(a.head, b.head)
a.printList()
예제 #20
0
def reverse(a):
    prev, current = None, a
    while current:
        next = current.next
        current.next = prev
        prev, current = current, next
    return prev

def mergeAlternate(a, b):
    head = tail = Node('x')
    while a and b:
        tail.next = a
        tail = tail.next
        a = a.next
        tail.next = b
        tail = tail.next
        b = b.next
    if a:
        tail.next = a
    if b:
        tail.next = b
    return head.next

a = LinkedList()
s = [10, 4, 7, 1, 3, 8, 9, 2, 0, 5, 6]
for i in s:
    a.append(i)
a.printList()
a.head = rearrange(a.head)
a.printList()
예제 #21
0
print("\_____/_|_| |_|_|\_\___|\__,_| \_____/_|___/\__|")

menu = """
    ╔═══ MENU ════════════════════════╗
    ║    1: Insert begin              ║
    ║    2: Insert end                ║
    ║    3: Insert position           ║
    ║    4: Delete begin              ║
    ║    5: Delete end                ║
    ║    6: Delete in position        ║
    ║    7: Insert random values      ║
    ║    0: Exit                      ║
    ╚═════════════════════════════════╝
"""

llist = LinkedList()

if __name__ == "__main__":

    while True:
        print(menu)

        option = int(input("Select an option: "))

        if option == 0:
            break

        elif option == 1:
            value = int(input("Type a value to insert at the beginning: "))
            llist.insert_begin(value)
예제 #22
0

def reverse(node, k, i):
    current, next, prev, count = node, None, None, 0
    if i == 0:
        while current and count < k:
            next = current.next
            current.next = prev
            prev = current
            current = next
            count += 1
    else:
        while current and count < k:
            prev, current, next = current, current.next, current.next
            count += 1
    if next:
        if i == 0:
            node.next = reverse(next, k, 1)
        else:
            prev.next = reverse(next, k, 0)
    return prev if i == 0 else node


l = LinkedList()
for i in range(1, 9):
    l.append(i)

l.printList()
l.head = reverse(l.head, 3, 0)
l.printList()
예제 #23
0
from list import Node
from list import LinkedList

def multiply(a, b):
    n1 = n2 = 0
    while a:
        n1 = n1 * 10 + a.data
        a = a.next
    while b:
        n2 = n2 * 10 + b.data
        b = b.next
    return n1 * n2


a = LinkedList()
a.append(9)
a.append(4)
a.append(6)
a.printList()
b = LinkedList()
b.append(8)
b.append(4)
b.printList()
print multiply(a.head, b.head)
예제 #24
0
    tail = head
    while a and b:
        if a.data <= b.data:
            tail.next = a
            a = a.next
        else:
            tail.next = b
            b = b.next
        tail = tail.next
    if a:
        tail.next = a
    if b:
        tail.next = b
    return head


def reverse(node):
    prev, current = None, node
    while current:
        next = current.next
        current.next = prev
        prev, current = current, next
    return prev
    
s = [10, 40, 53, 30, 67, 12, 89]
a = LinkedList()
for i in s:
    a.append(i)
a.printList()
a.head = sort(a.head)
a.printList()
예제 #25
0
            taill.next = a
            taill = taill.next
        elif a.data == x:
            taile.next = a
            taile = taile.next
        else:
            tailg.next = a
            tailg = tailg.next
        a.next = None
        a = nextA
    headl = headl.next
    headg = headg.next
    heade = heade.next
    if headl:
        if heade:
            taill.next = heade
        else:
            taill.next = headg
    if heade:
        taile.next = headg
    head = headl if headl else heade if heade else headg
    return head


a = LinkedList()
s = [1, 4, 3, 2, 5, 2, 3]
for i in s:
    a.append(i)
a.printList()
a.head = partition(a.head, 3)
a.printList()
예제 #26
0
#!/usr/bin/env python
# coding: utf-8

from list import LinkedList

userInputExpression = None
userInputCel = None
a = LinkedList()
b = LinkedList()


a.addFirst({
    'label': 'a1',
    'value': '5'
})



'''
while(True):
    userInputCel = raw_input('Where do you want insert? \n')
    userInputExpression = raw_input('Enter a math expression: \n')
    result = None
    if userInputCel[0].lower() == 'a':
        print 'A cedule'
        result = a.find({'label': userInputCel})
        if result == None:
            print 'not'
        else:
            print result.get_data()
    elif userInputCel[0].lower() == 'b':
예제 #27
0
        return
    prevL = None
    while True:
        if a == l:
            break
        a, l, prevL = a.next, l.next, l
    print "Loop begins at:", l.data
    prevL.next = None


def loopNode(a):
    fast, slow = a, a
    while fast and fast.next:
        fast = fast.next.next
        slow = slow.next
        if fast == slow:
            return fast
    return None


a = LinkedList()
for i in range(10):
    a.append(i)
a.printList()
detectAndRemoveLoop(a.head)
lastNode = a.head
while lastNode.next:
    lastNode = lastNode.next
lastNode.next = a.head.next.next.next.next.next
detectAndRemoveLoop(a.head)
a.printList()
    prevI, prevJ = None, None
    while j and k > 1:
        prevJ, j = j, j.next
        k -= 1
    if j is None:
        return newHead
    kthFromBegin, kthFromEnd = j, i
    while j.next:
        prevI, kthFromEnd = kthFromEnd, kthFromEnd.next
        j = j.next
    if kthFromBegin == kthFromEnd:
        return newHead
    if prevI is None:
        newHead = kthFromBegin
        prevJ.next = kthFromEnd
    elif prevJ is None:
        newHead = kthFromEnd
        prevI.next = kthFromBegin
    else:
        prevI.next = kthFromBegin
        prevJ.next = kthFromEnd
    kthFromBegin.next, kthFromEnd.next = kthFromEnd.next, kthFromBegin.next
    return newHead


a = LinkedList()
for i in range(1, 9):
    a.append(i)
a.printList()
a.head = swap(a.head, 1)
a.printList()
예제 #29
0
from list import LinkedList
from node import Node

print "\nCreating LinkedList from python list"
my_list = LinkedList([Node(2), None, Node(0), Node(0), Node(4)])
my_list.to_string()

print "\nAdding single node"
my_list.add_node(Node(5))
my_list.to_string()

print "\nAdding nodes from python tuple"
my_list.add_nodes((Node(0), Node(20), Node(-1)))
my_list.to_string()
예제 #30
0

def deleteMiddlePoints(node):
    while node and node.next and node.next.next:
        if node.data[0] == node.next.data[0] and node.data[
                0] == node.next.next.data[0]:
            node.next = node.next.next
            continue
        if node.data[1] == node.next.data[1] and node.data[
                1] == node.next.next.data[1]:
            node.next = node.next.next
            continue
        node = node.next


a = LinkedList()
a.append([0, 10])
a.append([1, 10])
a.append([5, 10])
a.append([7, 10])
a.append([7, 5])
a.append([20, 5])
a.append([40, 5])
a.printList()
deleteMiddlePoints(a.head)
a.printList()

b = LinkedList()
b.append([2, 3])
b.append([5, 3])
b.append([7, 3])
예제 #31
0
파일: stack.py 프로젝트: heliy/algorithms
 def clear(self):
     self.list = LinkedList()
예제 #32
0
    a = [0] * 3
    current = node
    while current:
        a[current.data] += 1
        current = current.next
    current = node
    i = 0
    while current and i < 3:
        current.data = i
        current = current.next
        a[i] -= 1
        if a[i] == 0:
            i += 1


l = LinkedList()
l.append(1)
l.append(0)
l.append(2)
l.append(2)
l.append(1)
l.append(1)
l.append(1)
l.append(0)
l.append(0)
l.append(0)
l.append(2)
l.append(1)
l.append(1)
l.append(2)
l.append(1)
예제 #33
0
from list import LinkedList

import time

import os

if __name__ == '__main__':
    my = LinkedList()
    my.insert(1)
    my.insert(2)
    my.insert(3)
    my.insert(5)
    my.insert(7)
    #my.disp()
    my.insertAfter(6,7)
    #my.disp()
    my.insertAfter(4,5)
    #my.disp()
    my.deleteBeg()
    my.insertEnd(0)
    my.disp()
    my.deleteEnd()
    my.disp()
    time.sleep(5)
    os.system("clear")
    my.deleteAny(5)
    my.disp()
예제 #34
0
    if l1 > l2:
        d = l1 - l2
        while d > 0:
            p = p.next
            d -= 1
    elif l2 < l1:
        d = l1 - l2
        while d > 0:
            q = q.next
            d -= 1
    while p != q:
        p, q = p.next, q.next
    return p.data


a = LinkedList()
b = LinkedList()

for i in range(8):
    a.append(i)

for j in range(8, 10):
    b.append(j)

b.head.next.next = a.head.next.next.next.next.next

a.printList()
b.printList()

print intersectionPoint(a, b)
예제 #35
0
파일: stack.py 프로젝트: heliy/algorithms
 def __init__(self):
     self.list = LinkedList()