Example #1
0
 def __init__(self, capacity):
     self.__data = LinkedList()
     self.__capacity = capacity
     self.__top = 0
Example #2
0
    def test_find_in_list_with_one_node(self):
        s_list_example = LinkedList()
        s_list_example.add_in_tail(Node(34))

        self.assertEqual(s_list_example.find_all(Node(2)), [])
        self.assertEqual(len(s_list_example.find_all(34)), 1)
Example #3
0
 def __init__(self):
     self.storage = LinkedList()
Example #4
0
 def test_insert_in_empty_list_with_none(self):
     s_list = LinkedList()
     s_list.insert(None, Node(2))
     self.assertEqual(s_list.len(), 1)
     self.assertEqual(s_list.head, s_list.tail)
Example #5
0
 def test_add_in_empty_list(self):
     s_list = LinkedList()
     s_list.add_in_tail(Node(5))
     self.assertEqual(s_list.len(), 1)
Example #6
0
# Program to find the middle element of a linked list

from linkedList import LinkedList


def middle_element(head):
    ptr1 = head
    ptr2 = head
    while ptr1:
        ptr1 = ptr1.get_next()
        if ptr1:
            ptr1 = ptr1.get_next()
            ptr2 = ptr2.get_next()
    return ptr2.get_data()


if __name__ == "__main__":
    ll_obj = LinkedList()
    ll_obj.insert(1)
    ll_obj.insert(2)
    ll_obj.insert(3)
    ll_obj.insert(4)
    ll_obj.insert(5)
    ll_obj.insert(6)
    ll_obj.insert_at_end(54)
    ll_obj.insert(123)
    ll_obj.printLinkedList(ll_obj.head)
    print "Middle element is: ", middle_element(ll_obj.head)
Example #7
0
# Write code to remove duplicates from an unsorted linked list.
# FOLLOW UP
# How would you solve this problem if a temporary buffer is not allowed?


from linkedList import LinkedList


ll = LinkedList()
ll.appendNode(1)
ll.appendNode(2)
ll.appendNode(2)
ll.appendNode(1)
ll.appendNode(2)
ll.appendNode(3)
ll.appendNode(3)
ll.appendNode(4)
ll.appendNode(4)
ll.appendNode(5)
ll.appendNode(5)
# ll.printList()
print('-----------')


def removeDups(ll):
    node = ll.head
    while node:
        checkNode = node.next
        prevCheckNode = node
        while checkNode:
        print(node.value)
Example #8
0
 def test_add_empty(self):
     self.assertEqual(lists_add(LinkedList(), LinkedList()).get_all(), [])
Example #9
0
    def test_find_all_in_1el(self):
        list2 = LinkedList()
        n1 = Node(55)
        list2.add_in_tail(n1)

        self.assertEqual(list2.find_all(n1.value), [n1])
def test_noDups():
    LL = LinkedList()
    LL.insert(1)
    LL.insert(2)
    LL.insert(3)
    assert LL == LL.removeDups()
Example #11
0
    def test_add_different_lists(self):
        list1 = LinkedList().create_list([55, 12, 43, 10, 14, 12, 55, 10, 5])
        list3 = LinkedList().create_list([55, 12, 43, 10, 14, 12, 55, 10])

        self.assertEqual(lists_add(list1, list3), False)
def test_remove():
    LL = LinkedList()
    LL.insert(1)
    LL.remove(1)
    assert None == LL.find(1)
def test_find():
    LL = LinkedList()
    LL.insert(1)
    LL.insert(2)
    assert None == LL.find(3)
Example #14
0
def main():
    LL = LinkedList()
    for i in range(1, 10, 2):
        LL.insert(i)
    LL.traverse()
Example #15
0
import time
import random
from linkedList import LinkedList

capacities = [10, 100, 1000, 10000, 100000, 1000000] # Capacidades solicitadas pelo professor

for c in capacities:
  linkedList = LinkedList(c)
  # Marcando o início da execução
  begin = int(round(time.time() * 1000))
  for i in range(linkedList.capacity):
    linkedList.addBegin(random.randint(0, linkedList.capacity))
  # Marcando o fim da execução
  end = int(round(time.time() * 1000))
  # Imprimindo o tempo de execução
  print('Tempo de execução para inserir {} elementos: {}ms'.format(linkedList.capacity, (end - begin)))
  
  # Armazenando a lista encadeada em um vetor
  linkedList_array = linkedList.toList()

  # Marcando o início da execução
  begin = int(round(time.time() * 1000))
  for i in range(linkedList.capacity):
    linkedList.removeBegin()
  # Marcando o fim da execução
  end = int(round(time.time() * 1000))
  # Imprimindo o tempo de execução
  print('Tempo de execução para remover {} elementos: {}ms'.format(linkedList.capacity, (end - begin)))

  # Marcando o início da execução
  begin = int(round(time.time() * 1000))
Example #16
0
    def test_mergeEmptyLists(self):
        list1 = LinkedList()
        list2 = LinkedList()

        self.assertEqual(mergeLists(list1, list2), [[], 1])
Example #17
0
 def __init__(self):
     self.size = 0
     # what data structure should we
     # use to store queue elements? - Linked List!
     self.storage = LinkedList()
Example #18
0
 def __init__(self):
     self.L = LinkedList()
def main():
    #init
    myList = LinkedList()
    #test isEmpty()
    print "isEmpty: " + str(myList.isEmpty())
    print "True if the initialized list is empty\n"
    #test size
    print "size: " + str(myList.size())
    print "Size of empty list should be 0\n"
    #test add
    myList.add(5)
    print "isEmpty: " + str(myList.isEmpty())
    print "Should be false since the list is no longer empty\n"
    print "size: " + str(myList.size())
    print "Size of list should now be 1 after adding one element\n"
    myList.add(4)
    myList.add(3)
    myList.add(2)
    myList.add(1)
    myList.add(0)
    print "size: " + str(myList.size())
    print "Size of list should now be 6 after adding five more elements\n"
    #test search
    print "search: " + str(myList.search(4))
    print "Search should return true since 4 is an element of the list\n"
    print "search: " + str(myList.search(6))
    print "Search should return false since 6 is not an element of the list\n"
    #test remove
    myList.remove(5)
    print "size: " + str(myList.size())
    print "Size of list should now be 4 after removing an element\n"
    print "search: " + str(myList.search(5))
    print "Search should return false since 5 is no longer an element of the list\n"
    #test printList
    print "printList:"
    myList.printList()
    print "Should print [0,1,2,3,4,5]"
    #test findAll
    print "findAll:"
    myList.findAll(6)
    print "Shoudn't find anything since 6 is not in the list\n"
    print "findAll:"
    myList.findAll(2)
    print "Should return [2] since there is only one element 2 in the index 2\n"
    myList.add(2)
    print "findAll:"
    myList.findAll(2)
    print "Should return [0,3] since another 2 was added to the head of the list\n"
    #test insert
    print "printList:"
    myList.printList()
    print "list before insertion\n"
    myList.insert(1, 1)
    myList.insert(7, 5)
    print "printList:"
    myList.printList()
    print "should return [2,1,0,1,2,3,4,5] after inserting 1 in position 1 and 5 in position 7(at the end)\n"
    #test popAtIndex
    print "popAtIndex: " + str(myList.popAtIndex(2))
    print "should return 0 since the element at position 2 was popped\n"
    print "printList:"
    myList.printList()
    print "list should now be [2,1,1,2,3,4,5] after popping 0\n"
    #test appendLast
    myList.appendLast(6)
    print "printList:"
    myList.printList()
    print "list should now be [2,1,1,2,3,4,5,6] after appending 6 using appendLast\n"
Example #20
0
from linkedList import LinkedList

_set = set()


def loopDetection(valMyList):
    vValue = None

    for i in valMyList:
        if not (i.value in _set):
            _set.add(i.value)
        else:
            vValue = i.value
            break

    return vValue


_list = LinkedList()
_list.addSeveral(["A", "B", "C", "D", "E", "C"])
print(loopDetection(_list))
Example #21
0
	first_node.next = second_node.next
	second_node.next = temp_node

	prev_node_1.next = second_node
	prev_node_2.next = first_node	



one = Node(1)
two = Node(2)
three = Node(3)
four = Node(4)
five = Node(5)
six = Node(6)

lnk = LinkedList()

lnk.insert_Head(one)
lnk.insert_End(two)
lnk.insert_End(three)
lnk.insert_End(four)
lnk.insert_End(five)
lnk.insert_End(six)	


swap_node(lnk, 2,1)
lnk.print_Node()



Example #22
0
def main():
    print('###################')
    l = test_LinkedList()
    print(l)

    print('###################')
    l.printList()

    print('###################')
    l.push('Sun')
    l.printList()

    print('###################')
    prev = l.head.next.next  # Tue
    l.insert(prev, 'TueEvening')
    l.printList()

    print('###################')
    l.insertAt(3, 'TueNight')
    l.printList()

    print('###################')
    l.append('Thur')
    l.printList()

    print('###################')
    l.deleteKey('Sun')
    l.printList()

    print('###################')
    l.deleteKey('TueEvening')
    l.printList()

    print('###################')
    l.deleteAt(0)
    l.printList()

    print('###################')
    l.deleteAt(2)
    l.printList()

    print('###################')
    l.deleteAt(20)
    l.printList()

    print('###################')
    print(l.length())

    print('###################')
    l = test_LinkedList()
    l.push('Sun')
    l.append('Thur')
    l.swap('Sun', 'Thur')
    l.printList()
    l.swap('Sun', 'Tue')
    l.printList()

    print('###################')
    l = test_LinkedList()
    l.push('Sun')
    l.append('Thur')
    l.printList()
    l.reverse()
    l.printList()

    print('###################')
    llist = LinkedList()
    llist.push(20)
    llist.push(4)
    llist.push(15)
    llist.push(10)
    # Create a loop for testing
    llist.head.next.next.next.next = llist.head

    if (llist.detectLoop()):
        print("Loop found")
    else:
        print("No Loop ")

    if (l.detectLoop()):
        print("Loop found")
    else:
        print("No Loop ")

    print('###################')
    if (llist.detectloopFloyd()):
        print("Loop found")
    else:
        print("No Loop ")

    if (l.detectloopFloyd()):
        print("Loop found")
    else:
        print("No Loop ")

    print('###################')
    l.rotate(3)
    l.printList()
    print('###################')
    l.rotate(2)
    l.printList()
Example #23
0
 def test_find_in_empty_list(self):
     s_list = LinkedList()
     self.assertIsNone(s_list.find(5))

def removeDupsThree(linkedList):
    ptr1 = linkedList.head
    while (ptr1.next):
        ptr2 = ptr1
        while (ptr2.next):
            if (ptr2.next.value == ptr1.value):
                ptr2.next = ptr2.next.next
            else:
                ptr2 = ptr2.next
        ptr1 = ptr1.next
    return linkedList


myLinkedList = LinkedList(1)
myLinkedList.append(1)
myLinkedList.append(2)
myLinkedList.append(3)
myLinkedList.append(3)
myLinkedList.append(3)
myLinkedList.append(4)
myLinkedList.append(1)
myLinkedList.append(3)
myLinkedList.append(4)
myLinkedList.append(3)
myLinkedList.append(3)
myLinkedList.append(8)
myLinkedList.append(99)
myLinkedList.append(100)
myLinkedList.append(5)
Example #25
0
 def test_find_in_empty_list(self):
     s_list_example = LinkedList()
     self.assertEqual(s_list_example.find_all(2), [])
Example #26
0
 def __init__(self):
     self._items = LinkedList()
Example #27
0
    def __init__(self, head=None):
        self.head = head

    def delete(self):
        some = self.head
        current = self.head
        while current.get_next():
            if current.get_data() == current.get_next().get_data():
                current.set_next(current.get_next().get_next())
            else:
                current = current.get_next()
        return some


if __name__ == "__main__":
    llObj = LinkedList()
    llObj.insert(1)
    llObj.insert_at_end(1)
    llObj.insert_at_end(2)
    llObj.insert_at_end(4)
    llObj.insert_at_end(4)
    llObj.insert_at_end(5)
    llObj.insert_at_end(10)
    print "Original",
    llObj.printLinkedList(llObj.head)

    dLL = RemoveDuplicatesFromSorted(llObj.head)
    newLL = dLL.traverse_and_delete()
    print "Unique element",
    llObj.printLinkedList(newLL.head)
Example #28
0
 def clear(self):
     self._items = LinkedList()
Example #29
0
    def initializeGameState(
        self, filename
    ):  #Initializes the game state specified in the textfile "filename"
        self.G = Grid(self.disp.size[0], self.disp.size[1])
        margin = 100
        lineCounter = 0
        y = 1
        x = 1
        firstRead = False
        f = open(filename, "r")
        lines = f.readlines()
        for line in lines:
            lineCounter += 1
            if not (
                    firstRead
            ):  #For the very first line of the file, initialize only n nodes in grid-like structure
                n = int(line)
                for labelCounter in range(1, n + 1):
                    currNode = Node(self.disp.BROWN, nodeSize, nodeSize,
                                    (margin * x), (margin * y), 0,
                                    labelCounter)
                    self.all_sprites_list.add(currNode)
                    x += 1
                    if ((margin * x)) >= (self.disp.size[0]):
                        x = 1
                        y += 1
                firstRead = True
            else:  #For the rest of the lines in the file, connect nodes as specified, in the given order, until an error is encountered.
                labels = line.split()
                startNode = self.all_sprites_list.sprites()[int(labels[0]) - 1]
                endNode = self.all_sprites_list.sprites()[int(labels[1]) - 1]
                if startNode.isFull() or endNode.isFull(
                ):  #Check if a move would exceed the allowed maximum degree
                    print(
                        "Line {} would cause a node to exceed degree 3".format(
                            lineCounter))
                    startNode = None
                    endNode = None
                    self.tempLst = LinkedList()
                    break
                elif (
                        labels[0] == labels[1]
                ):  #Check if a move asks for a loop, loops are allowed but the pathfinding algorithm can not handle it.
                    print("Loop detected at line {}, ending initialization".
                          format(lineCounter))
                    startNode = None
                    endNode = None
                    self.tempLst = LinkedList()
                    break
                try:
                    Grid.find_path(
                        startNode, endNode, self.tempLst, self.G,
                        self.all_sprites_list
                    )  #Try to find a path between the specified nodes.
                except:
                    print(
                        "Could not find a path between nodes {} and {} at line {} of initalize.txt.."
                        .format(labels[0], labels[1], lineCounter))
                    startNode = None
                    endNode = None
                    self.tempLst = LinkedList()
                    break

                #Place a new node on the found line, increment degrees, block nodes in the underlying grid, before moving on to the next line
                newNode = self.generate_node_on_path(startNode, endNode,
                                                     self.tempLst, self.G)
                startNode.incrementCounter()
                endNode.incrementCounter()
                self.all_sprites_list.add(newNode)
                #Grid.remove_node_area(newNode,self.G,0)
                Grid.block_nodes(self.tempLst, self.G, startNode, endNode,
                                 newNode)

                self.permLst.merge(self.tempLst)
                startNode = None
                endNode = None
                self.tempLst = LinkedList()
        #Initialization finished
        print("Done with initialization")
Example #30
0
import linkedList
from linkedList import Node, LinkedList

class Solution:
    def __init__(self):
        self.cache = {}

    def removeDups(self, head):
        curr = head
        dummy = Node(0)
        while curr is not None:
            if curr.val not in self.cache:
                self.cache[curr.val] = True
                dummy.next = curr
                dummy = dummy.next

            curr = curr.next
        return head

if __name__ == '__main__':
    ls = LinkedList()
    for i in [1, 3, 5, 2, 4, 2, 3, 5, 6]:
        node = Node(i)
        ls.addNode(node)
    ls.getValues()
    s = Solution()
    res = s.removeDups(ls.head)
    while res is not None:
        print(str(res.val) + ' -> ', end="")
        res = res.next
    print("None\n")