def add_link(head1, head2): carry = 0 dummy1 = LinkedList() dummy2 = LinkedList() dummy1.next = head1 dummy2.next = head2 p1 = dummy1 p2 = dummy2 while p1.next and p2.next: carry += p1.next.val + p2.next.val p1.next.val = carry % 10 carry /= 10 p1 = p1.next p2 = p2.next while p1.next: carry += p1.next.val p1.next.val = carry % 10 carry /= 10 p1 = p1.next while p2.next: carry += p2.next.val p1.next = LinkedList(carry % 10) carry /= 10 p1 = p1.next p2 = p2.next if carry: p1.next = LinkedList(carry) return dummy1.next
class Queue: def __init__(self): self.__elements = LinkedList() # Adds an element to this queue def enqueue(self, e): self.__elements.add(e) # Removes an element from this queue def dequeue(self): if self.getSize() == 0: return None else: return self.__elements.removeAt(0) # Return the size of the queue def getSize(self): return self.__elements.getSize() # Returns a string representation of the queue def __str__(self): return self.__elements.__str__() # Return true if queue is empty def isEmpty(self): return self.getSize() == 0
def testPrepend(): my_linked_list = LinkedList() for i in range(0,10): my_linked_list.prepend(i) print my_linked_list
class LLQueue(object): def __init__(self, size=0): self._list = LinkedList() self._size = size def enqueue(self, data): if (self._size > 0 and self._list.count < self._size): self._list.add(data) else: raise Exception("Too many items in the queue") def dequeue(self): if (self._list.count == 0): raise Exception("No items in the queue") node = self._list[0] del self._list[0] return node def isEmpty(self): return (self._list.count == 0) def clear(self): self._list.clear() @property def size(self): return self._size def __len__(self): return len(self._list)
def sum_list(l1, l2): """ returns a list which contains the addition of input two lists. """ lsum = LinkedList() carry = 0 l1_node = l1.head l2_node = l2.head while l1_node or l2_node: val = carry if l1_node: val += l1_node.value l1_node = l1_node.next if l2_node: val += l2_node.value l2_node = l2_node.next lsum.add(val % 10) carry = val / 10 if carry: lsum.add(carry) return lsum
class Queue: def __init__(self): self._ls = LinkedList() self.size = 0 def __str__(self): return "Queue contains:{0}".format(self._ls) def __iter__(self): return self def next(self): if not self.isEmpty(): j = self.dequeue() return j else: raise StopIteration() def enqueue(self,n): self._ls.append(n,None) self.size += 1 def dequeue(self): j = self._ls.popHead() self.size -= 1 return j.key def isEmpty(self): return self.size == 0 def show(self): self._ls.show()
def reverse(lst): reverse_lst = LinkedList() cur = lst.head while cur is not None: reverse_lst.insert(cur.get_key()) cur = cur.get_next() return reverse_lst
def test_delete(self): x = LinkedList([1,2,3,4,5]) val1 = x.delete(0) # 1st element val2 = x.delete(-1) # last element self.assertEqual(val1, 1) self.assertEqual(val2, 5) self.assertEqual(list(x), [2,3,4])
def read_file(file): ''' Read CSV File, Important Only Read column 1 and column 2 Parameters ---------- file : str, path of file path for file to read and fill dataset Returns ------- dataset: LinkedLink dataset ''' #Open File with open(file, 'rb') as csvfile: reader = csv.reader(csvfile) dataset=LinkedList() #for row in file: for row in reader: #if length of row >= 2: if len(row) >= 2: #add to LinkedList Float Row[0] and Row[1] try: dataset.add(( float(row[0]) , float(row[1]) )) except ValueError: log.warning("%s Problem whit row" % row[0]) else: #mesnsaje: row whit insuficient data. log.warning("row whit insuficient data or Empty Row") return dataset
def setUp(self): self.lst1 = LinkedList() self.lst2 = LinkedList() self.common_lst = LinkedList() self.lst1.insert(4) self.lst1.insert(2) self.lst1.insert(5) self.lst1.insert(8) self.lst1.insert(6) self.lst2.insert(3) self.lst2.insert(10) self.lst2.insert(8) self.common_lst.insert(3) self.common_lst.insert(2) self.common_lst.insert(5) self.common_lst.insert(7) current = self.lst1.head while current.get_next(): current = current.get_next() current.set_next(self.common_lst.head) current = self.lst2.head while current.get_next(): current = current.get_next() current.set_next(self.common_lst.head)
def test_insert_two(): l_list = LinkedList() l_list.insert("David") l_list.insert("Thomas") assert l_list.head.get_data() == "Thomas" head_next = l_list.head.get_next() assert head_next.get_data() == "David"
def add_two_numbers_adding_digit_reverse(lst1, lst2): lst = LinkedList() current_1 = lst1.head current_2 = lst2.head carry = 0 def get_digit(node1, node2): nonlocal carry num1 = 0 if node1 is None else node1.get_data() num2 = 0 if node2 is None else node2.get_data() value = num1 + num2 + carry if value >= 10: carry = 1 value %= 10 else: carry = 0 return value current_lst = lst.head while current_1 is not None or current_2 is not None or carry > 0: digit = get_digit(current_1, current_2) lst.insert(digit) current_1 = current_1.get_next() if current_1 is not None else None current_2 = current_2.get_next() if current_2 is not None else None return reverse_list(lst)
class Doc(): def __init__(self, doc): self.doc = doc; self.lines = LinkedList(); self.count = 1; self._iterator = None; self.documentFrequency = None; def reset(self): self.lines.reset(); self._iterator = None; def __str__(self): return '\n\t' + str(self.doc) + ', count:' + str(self.count) + self.lines.toString(','); def __lt__(self, other): return self.doc < other.doc; def __eq__(self, other): return self.doc == other.doc; def insertLine(self, line): line = IndexList.Line(int(line)); self.lines.insertSorted(line); def __iter__(self): return self; def next(self): if self._iterator is None: if self.lines._head is None: raise StopIteration self._iterator = self.lines._head; return self._iterator.value; self._iterator = self._iterator.next; if self._iterator is None: raise StopIteration return self._iterator.value;
def reverse_list(lst): new_lst = LinkedList() current = lst.head while current: new_lst.insert(current.get_data()) current = current.get_next() return new_lst
def insert(UI): #chop the UI to get only (position,item) command = UI[6:] #Regular expression: (\(\d*,.\)) expression = re.compile('(\(\d*,.*\))') if (expression.match(command) != None): #get the position pos = command[1] i = 2 while command[i] != ",": pos += command[i] i += 1 #Check that position is a number if (~pos.isdigit()): break #get the item item = command[i+1] i += 2 while command[i] != ")": item += command[i] i += 1 #called insert with pos, item LinkedList.insert(int(pos), item)
def test_insert_multi(): l_list = LinkedList() l_list.insert("Batman") l_list.insert("Superman") assert l_list.head.get_key() == "Superman" second = l_list.head.get_next() assert second.get_key() == "Batman"
def test_deleteNone(self): l = LinkedList(1) l.add(2) l.add(3) l.delete(5) self.assertEquals(l.val, 1) self.assertEquals(l.next.val, 2) self.assertEquals(l.next.next.val, 3)
def solution(): print "2-1 Remove dups. Pls enter linked list values, split by single space." raw_values = raw_input("values >> ") values = [float(val) for val in raw_values.strip().split()] l1 = LinkedList(values) l1.tranverse() removeDups(l1.head) l1.tranverse()
def solution(): print "2-2 return k-th to last, pls enter linked list value with space to split." raw_values = raw_input("values >> ") values = [float(i) for i in raw_values.strip().split()] k = int(raw_input("k >> ")) l1 = LinkedList(values) l1.tranverse() KthToLast_recu(l1.head, k)
def test_1(self): A = LinkedList() A.add(1) A.add(2) A.add(6) A.add(3) res = s.recursive_search(A, 2) self.assertIsNot(res,None)
def test_size(): l_list = LinkedList() assert l_list.size() == 0 l_list.insert("Batman") l_list.insert("Superman") assert l_list.size() == 2 l_list.delete("Superman") assert l_list.size() == 1
def test_add(self): l = LinkedList(0) l.add(1) l.add(2) l.add(3) self.assertEquals(0, l.val) self.assertEquals(1, l.next.val) self.assertEquals(2, l.next.next.val) self.assertEquals(3, l.next.next.next.val)
def test_add(self): myLinkedList = self.getLinkedList() myLinkedList.add(-1) self.assertEqual(myLinkedList.toArray()[0], Node(-1).getData()) # test empty list myLinkedList = LinkedList() myLinkedList.add(-1) self.assertEqual(myLinkedList.toArray()[0], Node(-1).getData())
def toList(n): result = LinkedList() t = n/10 while t>0: result.add_head(n%10) n = t t = n/10 result.add_head(n%10) return result
def testRemove(): my_linked_list = LinkedList() for i in range(0, 10): my_linked_list.append(i) for i in range(0, 10): print "removing " + str(i) my_linked_list.remove(i) print my_linked_list
def setUp(self): self.lst1 = LinkedList() self.lst2 = LinkedList() self.lst1.insert(4) self.lst1.insert(4) self.lst1.insert(3) self.lst2.insert(7) self.lst2.insert(5) self.lst2.insert(2)
def remove_duplicate_follow_up(LList): this_node = LList.get_root() result = LinkedList() while this_node: d = this_node.get_data() if not result.find(d): result.add_tail(d) this_node = this_node.get_next() return result
def test_delete_value_not_in_list(): l_list = LinkedList() l_list.insert("Jacob") l_list.insert("Pallymay") l_list.insert("Rasmus") with pytest.raises(ValueError): l_list.delete("Sunny")
def testLinkedList(): ll = LinkedList() while True: print ("Choose operation: ") print (" 1 - Add\n", "2 - Remove\n", "3 - Search\n", "4 - Size\n", "5 - Exit\n") choice = input() if choice == '1': ll = addll(ll) ll.__str__() elif choice == '2': ll == removell(ll) ll.__str__() elif choice == '3': searchKey(ll) ll.__str__() elif choice == '4': size(ll) ll.__str__() elif choice == '5': break else: print ("BAD Choice! Choose from 1 to 4 numbers")
def test(): data = LinkedList(['a', 'b', 'c', 'd', 'e']) data.head.next.next.next.next.next = data.head.next.next return loop_detector(data)
from LinkedList import LinkedList from LinkedList import Node def reverseLinkedList(node): if node == None or node.getNext() == None: return node new_node = reverseLinkedList(node.next) node.getNext().setNext(node) node.setNext(None) return new_node if __name__ == "__main__": ll1 = LinkedList() ll1.addEnd(5) ll1.addEnd(10) ll1.addEnd(15) ll1.addEnd(40) ll1.addEnd(12) ll1.addEnd(13) reversedHead = reverseLinkedList(ll1.getHeadNode()) ll1.traverseWithHead(reversedHead)
def test_append_empty(self) -> None: """test if append works on empty list""" lst = LinkedList() lst.append(0) assert lst.to_list() == [0]
def test_count_element_absent(self) -> None: """test count function when element is absent""" lst = LinkedList([0, 1, 2, 3, 4, 5, 6]) assert lst.count(10) == 0
def test_append_with_elements(self) -> None: """test if the append works on list with elements""" lst = LinkedList([1, 2, 3]) lst.append(0) assert lst.to_list() == [1, 2, 3, 0]
while new_value >= 10: new_value -= 10 new_carry += 1 old_carry, new_carry = new_carry, 0 list_sum.append(new_value) if ah is not None: ah = ah.next if bh is not None: bh = bh.next if old_carry != 0: list_sum.append(old_carry) print("Sum result: ", list_sum) return LinkedList(list_sum) assert str(sum_lists(LinkedList([1, 2, 3]), LinkedList([3, 2, 1]))) == str(LinkedList([4, 4, 4])) assert str(sum_lists(LinkedList([7, 1, 6]), LinkedList([5, 9, 2]))) == str( LinkedList([2, 1, 9])) ## 617 + 295 = 912 assert str(sum_lists(LinkedList([1, 5, 9]), LinkedList([2, 3, 6, 7]))) == str(LinkedList([3, 8, 5, 8])) assert str(sum_lists(LinkedList([9, 7, 8]), LinkedList([6, 8, 5]))) == str(LinkedList([5, 6, 4, 1])) ## TODO: solve the problem with the numbers in forward order (do something with adding zeroes) def sum_lists_forward(a: LinkedList, b: LinkedList) -> LinkedList: """ Sum two numbers, represented as LinkedLists
def addLLRe(nodeA, nodeB, carry): if nodeA is None and nodeB is None: return LinkedList() val = nodeA.value + nodeB.value return (addLLRe(nodeA.next, nodeB.next, val // 10)).add(val % 10)
return ans def addLLRe(nodeA, nodeB, carry): if nodeA is None and nodeB is None: return LinkedList() val = nodeA.value + nodeB.value return (addLLRe(nodeA.next, nodeB.next, val // 10)).add(val % 10) def sum_lists_followup(ll_a, ll_b): if getLengthLL(ll_a) < getLengthLL(ll_b): for i in range(getLengthLL(ll_b) - getLengthLL(ll_a)): ll_a.add_to_begining(0) elif getLengthLL(ll_a) > getLengthLL(ll_b): for i in range(getLengthLL(ll_a) - getLengthLL(ll_b)): ll_b.add_to_begining(0) return addLLRe(ll_a.head, ll_b.head, 0) ll_a = LinkedList() ll_a.generate(4, 0, 9) ll_b = LinkedList() ll_b.generate(4, 0, 9) print(ll_a) print(ll_b) print(sum_lists(ll_a, ll_b)) #print(sum_lists_followup(ll_a, ll_b))
from LinkedList import LinkedList linkedlist = LinkedList() linkedlist.insertend(10) linkedlist.insertend(20) linkedlist.insertend(30) linkedlist.insertend(40) linkedlist.insertbefore(5) linkedlist.insertposition(50,6) linkedlist.deletehead() linkedlist.deleteposition(5) linkedlist.deletematched(20) position=linkedlist.getposition(50) print(position) linkedlist.printlist()
i = 0 sortedList = [] for i in xrange(n): count = temp[i].head while count is not None: sortedList.append(count.data) count = count.next sortedList.reverse() self.sortedList = LinkedList().createList(sortedList) ## free ref2List = None temp = [] sortedList = [] def display(self): print "Unsorted list " self.unsortedList.display() # since its a linkedList print "Sorted List :" print self.sortedList.display() if __name__ == '__main__': arr = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68] llist = LinkedList() arrLList = llist.createList(arr) bs = BucketSort(arrLList, len(arr)) bs.sort() bs.display()
from LinkedList import LinkedList linked_list = LinkedList() linked_list.insertBeginning(1) linked_list.insertBeginning(5) linked_list.insertBeginning(3) linked_list.insertEnd(10) linked_list.insertAt(1, 4) linked_list.print_list() linked_list.deleteAt(1) #linked_list.delete(4) linked_list.print_list() linked_list.deleteAt(3) linked_list.print_list()
def main(): # Read each set line = sys.stdin.readline() items = line.strip().split() ll = LinkedList() # call the students function print(ll.count()) # Empty list, count should return 0 for item in items: ll.add(item) # call the students function print(ll.count()) # check that the first item removed from the list is the same as the last one added same = ll.remove() == items.pop() # call the students function again ... should be one shorter. print(ll.count()) while not ll.is_empty() and len(items) > 0: same = same and ll.remove() == items.pop() if not same or not ll.is_empty() or len(items) != 0: print("the list has been modified!")
from LinkedList import LinkedList def removeDuplicates(list): check_list = [] cur = list.head prev = None while cur: if cur.data in check_list: prev.next = cur.next cur = None else: check_list.append(cur.data) prev = cur cur = prev.next return list llist = LinkedList() llist.append(1) llist.append(6) llist.append(1) llist.append(4) llist.append(2) llist.append(2) llist.append(4) print("Removed Duplicates") removeDuplicates(llist).print_list()
fast = fakeNode fakeNode.next = head # maintain a difference of n between slow and fast. for i in range(n + 1): fast = fast.next while fast != None: fast = fast.next slow = slow.next to_del = slow.next slow.next = slow.next.next del to_del return fakeNode.next if __name__ == "__main__": head = None linked_list = LinkedList() head = linked_list.insert(head, 1, True) head = linked_list.insert(head, 2, True) head = linked_list.insert(head, 3, True) head = linked_list.insert(head, 4, True) head = linked_list.insert(head, 5, True) linked_list.printLL(head) res = Solution().deleteNthNodeFromLast(head, 2) print() linked_list.printLL(res)
def test_index_element_present(self) -> None: """test index function when element is present""" lst = LinkedList([0, 1, 2, 3, 4, 5, 6]) assert lst.index(2) == 2
pointer.set_nextnode(list2) else: pointer.set_nextnode(list1) return temp.nextnode node1 = LinkedListNode(1) node2 = LinkedListNode(2) node3 = LinkedListNode(3) node4 = LinkedListNode(4) node5 = LinkedListNode(5) node6 = LinkedListNode(6) node7 = LinkedListNode(7) node8 = LinkedListNode(8) LL1 = LinkedList() LL2 = LinkedList() LL1.addNode(node1) LL2.addNode(node2) LL1.addNode(node3) LL2.addNode(node4) LL1.addNode(node5) LL2.addNode(node6) LL1.addNode(node7) LL2.addNode(node8) print("First Linked list:") LL1.print_list() LL2.print_list() # print(" --- Test start")
def test_count_element_present(self) -> None: """test count function when element is present""" lst = LinkedList([0, 1, 2, 2, 4, 5, 6]) assert lst.count(2) == 2
current.next = current.next.next else: seen.add(current.next.value) current = current.next return l1 def remove_dups_no_buffer(l1): if l1.head is None: return -1 current = l1.head while current: runner = current while runner.next: if runner.next.value == current.value: runner.next = runner.next.next else: runner = runner.next current = current.next return l1.head ll = LinkedList() ll.generate(10, 0, 9) print("L1 before: " + str(ll)) remove_dups(ll) print("L1 after: " + str(ll)) ll.generate(10, 0, 9) print("L1 before: " + str(ll)) remove_dups_no_buffer(ll) print("L1 after: " + str(ll))
def test_getitem_slice_inbounds(self) -> None: """Test __getitem__ for a slice with well defined bounds""" lst = LinkedList([0, 1, 2, 3, 4, 5, 6]) assert lst[1:5].to_list() == [1, 2, 3, 4]
from LinkedList import LinkedList linkedlist = LinkedList() linkedlist.insertEnd(12) linkedlist.insertEnd(122) linkedlist.insertEnd(13) linkedlist.insertEnd(5) linkedlist.traverseList() linkedlist.remove(5) linkedlist.traverseList()
def test_getitem_slice_leftbound(self) -> None: """Test __getitem__ for a slice with well defined left bound but no right bound""" lst = LinkedList([0, 1, 2, 3, 4, 5, 6]) assert lst[1:].to_list() == [1, 2, 3, 4, 5, 6]
# Prompt: Implement an algorithm to delete a node in the middle (i.e any # node but the first and last node, not necessarily the exact middle) of a singly # linked list, given only access to the first node from LinkedList import LinkedList test = LinkedList(1) test.append(2) test.append(3) test.append(4) test.append(5) expected1 = LinkedList(1) expected1.append(2) expected1.append(4) expected1.append(5) test.remove_mid() assert (test == expected1)
def removeDuplicates(self, h): if h is None: return current = h seen = set([current.data]) while current.next: if current.next.data in seen: current.next = current.next.next else: seen.add(current.next.data) current = current.next obj = LinkedList() obj.add(1) obj.add(2) obj.add(3) obj.add(3) obj.add(4) obj.add(5) obj.add(7) obj.add(9) obj.add(9) obj.add(2) print("Before Removing Duplicates") obj.show()
n1 = n1.next n2 = n2.next return LinkedList([int(x) for x in str(result)]) def test_sum_lists(data): for ll1, ll2, expected in data: print(sum_lists(ll1, ll2)) print(expected) def test_follow_up(data): for ll1, ll2, expected in data: print(follow_up(ll1, ll2)) print(expected) if __name__ == "__main__": data = [(LinkedList([7, 1, 6]), LinkedList([5, 9, 2]), LinkedList([2, 1, 9]))] data2 = [(LinkedList([6, 1, 7]), LinkedList([2, 9, 5]), LinkedList([9, 1, 2]))] test_sum_lists(data) test_follow_up(data2)
from LinkedList import LinkedList linkedlist = LinkedList() linkedlist.insert_start(12) linkedlist.insert_start(13) linkedlist.insert_start(14) linkedlist.insert_start(15) linkedlist.traverse_list() linkedlist.remove(12) linkedlist.traverse_list()
from LinkedList import LinkedList link_list = LinkedList() link_list.add_node(4) link_list.add_node(5) link_list.add_node(3) link_list.add_node(1) link_list.add_node(2) def partition_around_x(link_list, value): lower_x_list = LinkedList() equal_x_list = LinkedList() greater_x_list = LinkedList() last_node_lower = None last_node_equal = None runner = link_list.head while runner != None: if runner.data < value: last_node_lower = lower_x_list.add_node(runner.data) elif runner.data == value: last_node_equal = equal_x_list.add_node(runner.data) else: greater_x_list.add_node(runner.data) runner = runner.next last_node_lower.next = equal_x_list.head last_node_equal.next = greater_x_list.head link_list.head = lower_x_list.head
def __init__(self): self.myList = LinkedList()
# Prompt: Implement an algorithm to find the kth to last element # of a singly linked list from LinkedList import LinkedList test = LinkedList(1) test.append(2) test.append(3) test.append(4) test.append(5) test.append(6) test.append(7) assert (test.get_kth_to_last(6) == 1) assert (test.get_kth_to_last(5) == 2) assert (test.get_kth_to_last(4) == 3) assert (test.get_kth_to_last(3) == 4) assert (test.get_kth_to_last(2) == 5) assert (test.get_kth_to_last(1) == 6)
from LinkedList import LinkedList link_list = LinkedList() link_list.add_node(1) link_list.add_node(2) node = link_list.add_node(3) link_list.add_node(4) link_list.add_node(5) def delete_middle_node(node): node.data = node.next.data node.next = node.next.next link_list.print_list() delete_middle_node(node) link_list.print_list()
ll2.add_to_beggining(0) else: for _ in range(len2 - len1): ll1.add_to_beggining(0) result = 0 runner1 = ll1.head runner2 = ll2.head while runner2 and runner1: result = result * 10 + runner1.value + runner2.value runner2 = runner2.next runner1 = runner1.next ll3 = LinkedList() for num in str(result): ll3.add(int(num)) return ll3 if __name__ == "__main__": ll1 = LinkedList() ll2 = LinkedList() ll1.generate(4, 1, 9) ll2.generate(5, 1, 9) print(ll1) print(ll2) ll3 = sum_list_followup(ll1, ll2) print(ll3)
def testPop(): my_linked_list = LinkedList() for i in range(0, 10): my_linked_list.append(i) for i in range(0, 10): node = my_linked_list.pop() print str(node._value) print "New LinkedList: " + str(my_linked_list)