def sumListsTwo(linkedList1, linkedList2): myLinkedList3 = LinkedList(None) carriage = 0 current1 = linkedList1.head current2 = linkedList2.head while (current1 or current2): if (current1 and current2): sum = current1.value + current2.value + carriage sumWithoutCarriage = sum if (sum >= 10 and current1.next != None and current2.next != None): carriage = math.floor(sum / 10) sumWithoutCarriage = sum % 10 elif (sum < 10 and current1.next != None and current2.next != None): carriage = 0 myLinkedList3.append(sumWithoutCarriage) current1 = current1.next current2 = current2.next elif (current1 == None): myLinkedList3.append(current2.value) current2 = current2.next elif (current2 == None): myLinkedList3.append(current1.value) current1 = current1.next myLinkedList3.print()
def alt_sum_lists(ll_a, ll_b): a_curr = ll_a.head b_curr = ll_b.head sum_ll = LinkedList() carryover = 0 while a_curr or b_curr: total = carryover if a_curr: total += a_curr.data a_curr = a_curr.next if b_curr: total += b_curr.data b_curr = b_curr.next sum_ll.add_node(Node(total%10)) carryover = total/10 if carryover: sum_ll.add_node(Node(carryover)) return sum_ll
def BackwordSum(ll1, ll2): s1 = StringifyList(ll1) s2 = StringifyList(ll2) s3 = str(int(s1[::-1]) + int(s2[::-1])) ll3 = LinkedList() for i in s3[::-1]: ll3.appendNode(i)
def run_noDups(): from linkedList import LinkedList f = open(INPUT_FILE,'r') w = open(OUTPUT_FILE,'w') count = 0 lst = LinkedList() # writes field headers to file w.write('sourceStreetAddress' + "\t" + 'sourceLocality' + "\t" + 'sourceAdministrativeArea' + "\t" + 'sourceCountry' + "\t" + 'resultStatus' + "\t" + 'resultGeomType' + "\t" + 'resultLat' + "\t" + 'resultLon' + "\t" + 'resultFormatted' + "\t" + 'URL' + "\t" + 'note' + "\n") #reads lines from source file street_address = f.readline() print street_address while street_address : if lst.add(street_address): # sends address to function address = getCoord(street_address) # delay for API constraints while address == 'OVER_QUERY_LIMIT': sleep(10) address = getCoord(street_address) # checks for None in geocode result and converts - NOT WORKING if address is None: print str(street_address.strip()) + ": " + str(address) + "\n" w.write(str(address) + "\n".encode('utf-8')) # returns geocode result - NOT WORKING else: print str(street_address.strip()) + ": " + str(address) + "\n" w.write(str(address) + "\n".encode('utf-8')) count += 1 street_address = f.readline() return street_address f.close() w.close() # Count not working print count + "unique coordinates were queried"
def reversedLinkedList(linkedList): resultLinkedList = LinkedList() current = linkedList.head while (current): resultLinkedList.prepend(current.value) current = current.next return resultLinkedList
def test_add(self): list1 = LinkedList().create_list([55, 12, 43, 10, 14, 12, 55, 10, 5]) list1_copy = LinkedList().create_list( [55, 12, 43, 10, 14, 12, 55, 10, 5]) self.assertEqual(lists_add(list1, list1_copy).get_all(), [ 110, 24, 86, 20, 28, 24, 110, 20, 10])
def createFutureEventList(self): self.futureEventList = LinkedList() self.futureEventList.insertNode(setEventType(ARRIVAL, 's', 0), self.arrivalTime) # First stage events self.futureEventList.insertNode(setEventType(BREAK, 's', 0), self.stage.breakTime) # Second stage events # Common cashiers for index, cashier in enumerate(self.cashierStage.commonCashiers): if cashier.breakTime != IDLE: self.futureEventList.insertNode( setEventType(BREAK, 'c', index), cashier.breakTime) if cashier.operationalTime != IDLE: self.futureEventList.insertNode( setEventType(OPERATION, 'c', index), cashier.operationalTime) # Common cashiers for index, cashier in enumerate(self.cashierStage.prioritaryCashiers): if cashier.breakTime != IDLE: self.futureEventList.insertNode( setEventType(BREAK, 'p', index), cashier.breakTime) if cashier.operationalTime != IDLE: self.futureEventList.insertNode( setEventType(OPERATION, 'p', index), cashier.operationalTime)
def __init__(self, x, timeWindow=0.1, sampleRate=44100, percentileLevel=95, wlevels=4, dbName='db8'): self.x = x self.timeWindow = timeWindow self.windowSamples = int(timeWindow * sampleRate) self.wlevels = wlevels self.dbName = dbName self.windows = list() self.sortedWindows = list() self.noiseWindows = None self.noiseLinked = LinkedList() self.signalWindows = None self.signalLinked = LinkedList() self.percentileLevel = percentileLevel self.noiseData = None self.noiseWavelets = list() self.threshold = None self.extractWindows() print("Noise profiler finished")
class LStack: #CONSTRUCTOR def __init__(self): self.datastore = LinkedList() #CONSTRUCTOR #METHODS def push(self, value): newNode = Node(value, self.datastore.head) self.datastore.head = newNode def pop(self): nodeToDelete = self.datastore.head self.datastore.head = self.datastore.head.next return nodeToDelete.value def isEmpty(self): return self.datastore.isEmpty() def top(self): return self.datastore.head.value def print(self): self.datastore.print()
def add(first, second): diff = first.size() - second.size() if diff != 0: if diff>0: while diff != 0: second.append(0) diff -= 1 else: while diff*-1 != 0: first.append(0) diff += 1 result = LinkedList() carry = False currentF = first.head currentS = second.head carry = 0 while currentF: tSum = currentF.data + currentS.data + carry if tSum>=10: carry = 1 tSum = tSum - 10 else: carry = 0 result.append(tSum) currentS = currentS.next_node currentF = currentF.next_node if carry == 1: result.append(1) return result
def run_noDups(): from linkedList import LinkedList f = open(INPUT_FILE,'r') w = open(OUTPUT_FILE,'w') count = 0 lst = LinkedList() w.write('sourceStreetAddress' + "\t" + 'sourceLocality' + "\t" + 'sourceAdministrativeArea' + "\t" + 'sourceCountry' + "\t" + 'resultStatus' + "\t" + 'resultGeomType' + "\t" + 'resultLat' + "\t" + 'resultLon' + "\t" + 'resultFormatted' + "\t" + 'URL' + "\t" + 'note' + "\n") street_address = f.readline() print street_address while street_address : if lst.add(street_address): address = getCoord(street_address) while address == 'OVER_QUERY_LIMIT': sleep(10) address = getCoord(street_address) if address is None: print str(street_address.strip()) + ": " + str(getReducedCoord(street_address)) + "\n" w.write(str(getReducedCoord(street_address)) + "\n".encode('utf-8')) else: print str(street_address.strip()) + ": " + str(address) + "\n" w.write(str(address) + "\n".encode('utf-8')) count += 1 street_address = f.readline() return street_address f.close() w.close() # Count not working print count + "unique coordinates were queried"
class Queue(object): """Queue data structure, FIFO.""" def __init__(self, data=None): """If data is a LinkedList, then it makes a shallow copy""" self.ll = LinkedList() if data is not None: if isinstance(data, LinkedList): self.ll = data else: self.ll.insert_at_head(data) def enqueue(self, data): self.ll.insert_at_tail(data) def dequeue(self): ... def peek(self): return self.ll.get_at_head def __len__(self): return len(self.ll) def size(self): return len(self.ll)
def ForwordSum(ll1, ll2): s1 = StringifyList(ll1) s2 = StringifyList(ll2) s3 = str(int(s1) + int(s2)) ll3 = LinkedList() for i in s3: ll3.appendNode(i)
def sum_lists(ll_a,ll_b): a_str = "" b_str = "" a_curr = ll_a.head b_curr = ll_b.head while a_curr: a_str = str(a_curr.data) + a_str a_curr = a_curr.next while b_curr: b_str = str(b_curr.data) + b_str b_curr = b_curr.next total = int(a_str) + int(b_str) out = LinkedList() while total: remainder = total % 10 temp_node = Node(remainder) if not out.head: out.head = temp_node else: out.add_node(temp_node) total = (total - remainder)/10 return out
def test_LinkedList(): l1 = LinkedList() l1.head = Node('Mon') e2 = Node('Tue') e3 = Node('Wed') l1.head.next = e2 # link first Node to second Node e2.next = e3 # link secodn node to third Node return l1
def __init__(self, data=None): """If data is a LinkedList, then it makes a shallow copy""" self.ll = LinkedList() if data is not None: if isinstance(data, LinkedList): self.ll = data else: self.ll.insert_at_head(data)
def image_to_linked_list(self): for row in range(0,self.imgRows,1): list=LinkedList() for col in range(0,self.imgCols,1): pixel=self.imgBGR[row][col] list.at_start(pixel) self.imgList.at_start(list) #add row
def test_delete_in_head(self): list1 = LinkedList().create_list([55, 12, 43, 10, 14, 12, 55, 10, 5]) list1.delete(55) self.assertEqual(list1.get_all(), [12, 43, 10, 14, 12, 55, 10, 5]) self.assertEqual(list1.len(), 8) self.assertEqual(list1.get_head(), list1.find(12)) self.assertEqual(list1.get_tail(), list1.find(5))
class Stack(): def __init__(self, top=None): self.ll = LinkedList(top) def push(self, new_element): self.ll.insert_first(new_element) def pop(self): return self.ll.delete_first()
def __init__(self,source): self.imgBGR = cv.imread(source,1) self.imgRows,self.imgCols,z = self.imgBGR.shape self.orderImage=np.zeros((self.imgRows,self.imgCols,z),np.uint8) self.imgList=LinkedList() print(self.imgBGR.shape)
def setUp(self): # Set up Nodes e1 = Node(1) e2 = Node(2) e3 = Node(3) # Start setting up a LinkedList self.ll = LinkedList(e1) self.ll.append(e2) self.ll.append(e3)
def main(): #create linked list node1 = 'apples' node2 = 'bananas' node3 = 'strawberries' node4 = 'blueberries' ll = LinkedList() ll.head = Node('node1') ll.insert()
def test_delete_from_short_list(self): s_list_example = LinkedList() s_list_example.add_in_tail(Node(5)) s_list_example.add_in_tail(Node(1)) s_list_example.add_in_tail(Node(6)) s_list_example.add_in_tail(Node(8)) s_list_example.add_in_tail(Node(11)) s_list_example.add_in_tail(Node(77)) s_list_example.delete(5) self.assertEqual(s_list_example.head.value, 1)
def test_insert_in_tail(self): list3 = LinkedList().create_list([20, 55, 12, 10, 55]) n6 = Node(22) list3.insert(list3.get_tail(), n6) self.assertEqual(list3.get_all(), [20, 55, 12, 10, 55, 22]) self.assertEqual(list3.get_head(), list3.find(20)) self.assertEqual(list3.get_tail(), n6)
class Queue2(object): def __init__(self): self.L=LinkedList() def Enqueue(self,key): self.L.PushBack(key) def Dequeue(self): return self.L.PopFront() def isEmpty(self): return self.L.isEmpty()
def lists_add(list1, list2): if list1.len() != list2.len(): return False else: result_list = LinkedList() node1 = list1.get_head() node2 = list2.get_head() while node1 != None: result_list.add_in_tail(Node(node1.value + node2.value)) node1 = node1.next node2 = node2.next return result_list
def test_loop(): LL = LinkedList() node = Node(3) LL.head = Node(1) LL.head.next = Node(2) LL.head.next.next = node LL.head.next.next.next = Node(4) LL.head.next.next.next.next = Node(5) LL.head.next.next.next.next = node assert node == loopDetection(LL)
def createRandomPosting(): ##Creating a randomly generated posting list of given size ##between given integers SIZE = 3 START = 1 END = 10000 lyst = LinkedList() for i in range(SIZE): lyst.add(random.randint(START, END)) return lyst
def test_delete_from_1el(self): list4 = LinkedList() n1 = Node(55) list4.add_in_tail(n1) list4.delete(55) self.assertEqual(list4.get_all(), []) self.assertEqual(list4.get_head(), None) self.assertEqual(list4.get_tail(), None)
def sumLinkedLists(LL1, LL2): LL3 = LinkedList() # init result linked list curr1 = LL1.head # get heads of both input linked lists curr2 = LL2.head carry = 0 # carryover value while ((curr1 is not None) | (curr2 is not None)): resultSum = curr1.data + curr2.data # add data LL3.insert( (resultSum % 10) + carry) # get one's place digit then add carry carry = 1 if resultSum >= 10 else 0 # determing carry curr1 = curr1.next # move pointers along curr2 = curr2.next return LL3
class Stack: def __init__(self): self.storage = LinkedList() def __len__(self): return self.storage.get_length() def push(self, value): self.storage.add_at_head(value) return def pop(self): return self.storage.remove_head()
class TestStringMethods(unittest.TestCase): def setUp(self): # Set up Nodes e1 = Node(1) e2 = Node(2) e3 = Node(3) # Start setting up a LinkedList self.ll = LinkedList(e1) self.ll.append(e2) self.ll.append(e3) def test_get_linkedlist_value(self): """ Test linkedlist value between 1 and 3, should return value from 1 to 3 """ self.assertEqual(self.ll.head.value, 1) self.assertEqual(self.ll.head.next.value, 2) self.assertEqual(self.ll.head.next.next.value, 3) def test_node_not_in_list(self): self.assertEqual(self.ll.head.next.next.next, None) def test_get_position_value(self): """ get_position will return the element at a certain position. """ self.assertEqual(self.ll.get_position(1).value, 1) self.assertEqual(self.ll.get_position(2).value, 2) self.assertEqual(self.ll.get_position(3).value, 3) def test_insert_position(self): """ insert function will add an element to a particular spot in the list. Assume the first position is "1". Inserting at position 3 means between the 2nd and 3rd elements. """ e4 = Node(4) self.ll.insert(e4, 3) self.assertEqual(self.ll.get_position(3).value, 4) def test_delete_value(self): """ delete will delete the first element with that particular value. """ self.ll.delete(1) self.assertEqual(self.ll.get_position(1).value, 2) self.assertEqual(self.ll.get_position(2).value, 3)
def test_size(): LL = LinkedList() LL.insert(1) assert 1 == LL.size() LL.remove(1) assert 0 == LL.size()
def test_delete_in_tail(self): list1 = LinkedList().create_list([12, 10, 14, 12, 55, 10, 5]) list1.delete(5) self.assertEqual(list1.get_all(), [12, 10, 14, 12, 55, 10]) self.assertEqual(list1.get_head(), list1.find_all(12)[0]) self.assertEqual(list1.get_tail(), list1.find_all(10)[1])
def test_find_in_long_random_list(self): s_list_example = LinkedList() listLength = randint(10000, 1000000) valuesForFind = [] for i in range(1, listLength): value = randint(1, 1000) s_list_example.add_in_tail(Node(value)) valuesForFind.append(value) for i in range(100): index = randint(0, len(valuesForFind)) value = valuesForFind[index] self.assertIsNotNone(s_list_example.find(value))
class QueueAsLinkedList(Queue): __slots__ = ['__list'] def __init__(self): super(QueueAsLinkedList, self).__init__() self.__list = LinkedList() def purge(self): self.__list.purge() def getHead(self): return self.__list.getFirst() # getfirst ya hace las siguientes comprobaciones #if self.__list.getIsEmpty(): # raise IndexError("Empty") #else: # return self.__list.getHead() def enqueue(self, obj): self.__list.append(obj) # el append de linkedlist ya hace las comprobaciones pertinentes def dequeue(self): item = self.__list.getFirst() self.__list.extract(self.__list.getFirst()) return item # el extract de linkedlist ya hace las comprobaciones de lista vacia def accept(self, visitor): assert isinstance(visitor, Visitor) ptr = self.__list.head while ptr is not None: visitor.visit(ptr.data) if visitor.isDone: return ptr = ptr.next def getIsEmpty(self): return self.__list.getIsEmpty() class Iterator(Iterator): __slots__ = ['__position'] def __init__(self, queue): super(QueueAsLinkedList.Iterator,self).__init__(queue) self.__position = None def next(self): if self.__position is None: self.__position = self.container._QueueAsLinkedList__list.head else: self.__position = self.__position.next if self.__position is None: raise StopIteration return self.__position.data def __iter__(self): return self.Iterator(self) def _compareTo(self, obj): assert isinstance(self, obj.__class__) raise NotImplementedError
def __init__(self): """ (OrderedSequenceAsLinkedList) -> None Constructs an ordered sequence. """ super(OrderedSequenceAsLinkedList, self).__init__() self.__list = LinkedList() self.count = 0
class LStack: #CONSTRUCTOR def __init__(self): self.datastore = LinkedList() #CONSTRUCTOR #METHODS def push(self, value): newNode = Node(value, self.datastore.head) self.datastore.head = newNode def pop(self): nodeToDelete = self.datastore.head self.datastore.head = self.datastore.head.next return nodeToDelete.value def isEmpty(self): return self.datastore.isEmpty() def top(self): return self.datastore.head.value def print(self): self.datastore.print()
def addLinkedLists (LinkedList1, LinkedList2): # First we need to add the values to a queue in order to sum them queue1 = Queue() current1 = LinkedList1.head while current1: queue1.enqueue(current1.data) current1 = current1.next queue2 = Queue() current2 = LinkedList2.head while current2: queue2.enqueue(current2.data) current2 = current2.next # Now we need to add the numbers in reverse times 10^n sumValues = 0 exp = 0 while not queue1.isEmpty() or not queue2.isEmpty(): sumValues += (queue1.dequeue() + queue2.dequeue()) * (10 ** exp) exp += 1 print(sumValues) # The answer is actually sumValues reversed finalAnswer = 0 if sumValues < 0: # because we are using string slice [::-1] operator to reverse, we need to check if negative sumValues = abs(sumValues) finalAnswer = int(str(sumValues)[::-1]) * -1 else: finalAnswer = int(str(sumValues)[::-1]) # Finally, we need to create a new linked List with the digits in order and return it finalList = LinkedList() while finalAnswer / 10 > 0: finalList.insertLast(finalAnswer % 10) finalAnswer = finalAnswer // 10 return finalList
def run_noDups(): from linkedList import LinkedList f = open(INPUT_FILE,'r') w = open(OUTPUT_FILE,'w') count = 0 lst = LinkedList() nation = f.readline() while nation : if lst.add(nation): coord = getCoord(nation) while coord == 'OVER_QUERY_LIMIT': sleep(1) coord = getCoord(nation) print nation.strip() + ": " + coord + "\n" w.write(coord + "\n") count += 1 nation = f.readline() f.close() w.close() print count + "unique nations were queried"
def traverse_and_delete(self): """ Traverse the linked list and insert unique elements in new list :return: new linked list containing unique elements """ current = self.head next_next = None new_list = LinkedList() if not current: return while current.get_next(): if current.get_data() == current.get_next().get_data(): new_list.insert_at_end(current.get_data()) next_next = current.get_next().get_next() current = next_next else: new_list.insert_at_end(current.get_data()) current = current.get_next() new_list.insert_at_end(current.get_data()) return new_list
head2.next = curr2 curr2 = None elif curr2.next and curr1.value<curr2.next.value: tmp = curr2.next curr2.next = curr1 curr1 = curr1.next curr2.next.next = tmp curr2 = None elif not curr2.next: curr2.next = curr1 curr1 = curr1.next curr2.next.next = None curr2 = None else: curr2 = curr2.next return head2 aList = LinkedList() aList.add(9) print aList.displayLinkedListFromNode(insertionSort(aList.head)) aList.add(4) print aList.displayLinkedListFromNode(insertionSort(aList.head)) aList.add(8) aList.add(3) aList.add(7) aList.add(6) print aList print aList.displayLinkedListFromNode(insertionSort(aList.head))
""" Show recursive solution for sum of values in Linked List. This was example from module 4. Recursive Structures Author: George Heineman """ from linkedList import LinkedList def sumList(n): # Base case if n is None: return 0 # Action and Recursive Step return n.value + sumList(n.next) if __name__ == '__main__': myList = LinkedList() myList.prepend(11) myList.prepend(10) myList.prepend(8) print ("Sum (", sumList(myList.head), ") should be 29.")
total += a_curr.data a_curr = a_curr.next if b_curr: total += b_curr.data b_curr = b_curr.next sum_ll.add_node(Node(total%10)) carryover = total/10 if carryover: sum_ll.add_node(Node(carryover)) return sum_ll if __name__ == '__main__': a = LinkedList(Node(7, Node(1, Node(6)))) b = LinkedList(Node(5, Node(9, Node(2)))) print a.as_string() print b.as_string() print "adding the lists (617 + 295 = 912) my two ways: " print sum_lists(a, b).as_string() print alt_sum_lists(a, b).as_string() print "uneven lists: 17 + 295 = 312" c = LinkedList(Node(7, Node(1))) d = LinkedList(Node(5, Node(9, Node(2)))) print c.as_string()
def __init__(self): self.datastore = LinkedList()
def __init__(self): super(QueueAsLinkedList, self).__init__() self.__list = LinkedList()
# 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)
p2 = linkedlist.head.next while p2 != None: """ beautiful solution!!!""" # two runner pointer p1 and p2, where p2 = p1.next, if p1.value > p2.value, assign p2 to head, so head always point to smaller part! if p2.value < x: p1.next = p2.next p2.next = linkedlist.head linkedlist.head = p2 p2 = p1.next else: p1 = p1.next p2 = p1.next #----------------test----------------- aList = LinkedList() aList.add(6) aList.add(6) aList.add(3) aList.add(7) aList.add(6) aList.add(1) aList.add(9) aList.add(8) aList.add(2) x = 5 print aList, " , x=5" partition(aList, x) print aList
def __init__(self): super(StackAsLinkedList, self).__init__() self.__list = LinkedList()
from linkedList import LinkedList data = LinkedList() data.insert('F') data.insert('O') data.insert('L') data.insert('L') data.insert('O') data.insert('W') data.insert(' ') data.insert('U') data.insert('P') def removeDups(data): node = data.head while node: nestNode = data.head while nestNode: if (nestNode.data == node.data) and nestNode != node: data.delete(node.data) nestNode = nestNode.next_node node = node.next_node data.printList() print 'deduping' removeDups(data) data.printList()
if current.next == None: #check if we are on last node previous.next = None else: current.data = current.next.data current.next = current.next.next # move to next previous = current current = current.next # if not in dict - this isn't a dup. add it to dict and move on else: nodes_seen.setdefault(current.data, True) previous = current current = current.next return ll my_list = LinkedList(Node(2, Node(4, Node(1, Node(2, Node(7, Node(1))))))) print "testing having to remove last node" print "my_list before: ", my_list.as_string() remove_dups(my_list) print "my_list after: ", my_list.as_string() print "testing not having to remove last node: " another_list = LinkedList(Node(4, Node(4, Node(1, Node(2, Node(7)))))) print "another_list before: ", another_list.as_string() remove_dups(another_list) print "another_list after: ", another_list.as_string()
def setUp(self): self.link = LinkedList()
output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 (or similar, order within greater or lesser doesn't matter) """ # create list of all nodes >= to partition value move_list = [] # go through our LL and take out the nodes >= and add to our move_list current = ll.head while current: if current.data >= x: move_node = Node(current.data) move_list.append(move_node) current.data = current.next.data current.next = current.next.next else: current = current.next for n in move_list: ll.add_node(n) my_ll = LinkedList(Node(3, Node(5, Node(8, Node(5, Node(9, Node(2, Node(1)))))))) print my_ll.as_string() partition(my_ll, 5) print my_ll.as_string()
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)
class TestLinkedList(unittest.TestCase): def setUp(self): self.link = LinkedList() def tearDown(self): self.link = None def test_basic(self): """Basic test.""" self.assertEqual(0, len(self.link)) self.link.prepend(99) self.assertEqual(1, len(self.link)) self.link.prepend(30) self.assertEqual(30, self.link.pop()) self.assertEqual(99, self.link.pop()) def test_stack(self): """Basic test.""" self.assertEqual(0, len(self.link)) self.link.prepend(99) self.assertEqual(1, len(self.link)) self.link.prepend(30) self.assertFalse(self.link.remove(19)) self.assertTrue(self.link.remove(30)) self.assertEqual(1, len(self.link)) self.assertFalse(self.link.remove(30)) self.assertEqual(1, len(self.link)) self.assertTrue(self.link.remove(99)) self.assertEqual(0, len(self.link)) def test_iterators(self): """Iterators""" self.link.prepend(99) self.assertEqual(1, len(self.link)) self.link.prepend(30) self.assertTrue(30 in self.link) self.assertFalse(15 in self.link) def test_infinite(self): """Test infinite check.""" node0 = LinkedNode(0) node1 = LinkedNode(10) node2 = LinkedNode(20) node3 = LinkedNode(30) node1.next = node2 node2.next = node3 self.assertFalse(node1.checkInfinite()) node3.next = node2 # WARNING CYCLE self.assertTrue(node1.checkInfinite()) node0.next = node1 self.assertTrue(node0.checkInfinite())
while(tmp.next!=pivot): tmp = tmp.next tmp.next = None # need to break the link for the first half newHead = quicksortHelper(newHead,tmp) tmp = getTail(newHead) # the tail of the first half should be re-fetch tmp.next = pivot if newTail!=pivot: pivot.next = quicksortHelper(pivot.next,newTail) return newHead def quickSort(head): if head: tail = getTail(head) return quicksortHelper(head,tail) aList = LinkedList() aList.add(9) aList.add(4) aList.add(8) aList.add(3) aList.add(7) aList.add(6) print aList print aList.displayLinkedListFromNode(aList.head.next) print aList.displayLinkedListFromNode(quickSort(aList.head))
from linkedList import Node from linkedList import LinkedList n1 = Node(1) n2 = Node(2) n3 = Node(3) lst = LinkedList() lst.add_first(n1) lst.add_first(n2) lst.add_first(n3) lst.print_list()
from linkedList import LinkedList data = LinkedList() data.append('A') data.append('B') data.append('C') data.append('D') data.append('E') data.append('F') data.append('G') def kthToTheLast(data, k): size = data.size() if k > size: raise ValueError('K larger than Data') node = data.head for i in range(0,size-k): node = node.next_node return node.data print kthToTheLast(data, 2)