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
class LinkedQueue: def __init__(self): self._items = LinkedList() def is_empty(self): return len(self._items) == 0 def __len__(self): return len(self._items) def __iter__(self): iter(self._items) def clear(self): self._items = LinkedList() def add_front(self, item): self._items.append_head(item) def add_rear(self, item): self._items.append(item) def remove_front(self): return self._items.pop_head() def remove_rear(self): return self._items.pop_tail()
def partitionTwo(linkedList, value): myLinkedList = LinkedList(None) current = linkedList.head while (current): if (current.value < value): myLinkedList.prepend(current.value) elif (current.value >= value): myLinkedList.append(current.value) current = current.next current = None return myLinkedList
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)
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
class LinkedQueue: def __init__(self): self._items = LinkedList() def is_empty(self): return len(self._items) == 0 def __len__(self): return len(self._items) def __iter__(self): iter(self._items) def clear(self): self._items = LinkedList() def enqueue(self, item): self._items.append(item) def dequeue(self): return self._items.pop_head()
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 main(): llist1 = LinkedList() llist1.append(Node(2)) llist1.append(Node(4)) llist1.append(Node(3)) #llist1.printNodes() llist2 = LinkedList() llist2.append(Node(5)) llist2.append(Node(6)) llist2.append(Node(4)) #llist2.printNodes() add2Sum(llist1, llist2)
def test_append(self): print('Test: append on an empty list') linked_list = LinkedList(None) linked_list.append(10) assert_equal(linked_list.get_all_data(), [10]) print('Test: append a None') linked_list.append(None) assert_equal(linked_list.get_all_data(), [10]) print('Test: append general case') linked_list.append('a') linked_list.append('bc') assert_equal(linked_list.get_all_data(), [10, 'a', 'bc']) print('Success: test_append\n')
for i in range(0, int(l1 - l2)): p1 = p1.next else: for i in range(0, int(l2 - l1)): p2 = p2.next while (p1 and p2): if (p1 == p2): intersectionNode = p1 break p1 = p1.next p2 = p2.next return intersectionNode myLinkedList3 = LinkedList() myLinkedList3.append(111) myLinkedList3.append(101) myLinkedList3.append(102) myLinkedList1 = LinkedList() myLinkedList1.append(88) myLinkedList1.append(2) myLinkedList1.append(100) p1 = myLinkedList1.head while (p1.next): p1 = p1.next p1.next = myLinkedList3.head myLinkedList2 = LinkedList() myLinkedList2.append(4)
from linkedList import LinkedList def returnKthToLast(linkedList, k): ptr1 = linkedList.head ptr2 = linkedList.head for i in range(0, k - 1): try: ptr2 = ptr2.next except Exception as exception: return exception while (ptr1.next and ptr2.next): ptr1 = ptr1.next ptr2 = ptr2.next return ptr1.value myLinkedList = LinkedList(1) myLinkedList.append(2) myLinkedList.append(3) myLinkedList.append(4) myLinkedList.append(5) myLinkedList.append(6) print(returnKthToLast(myLinkedList, 3))
oddCount = oddCount + 1 if (oddCount > 1): isPalindrome = False return isPalindrome def linkedListPalindromeTwo(linkedList): myReversedLinkedList = reversedLinkedList(linkedList) p1 = linkedList.head p2 = myReversedLinkedList.head isPalindrome = True while (p1 and p2): if (p1.value != p2.value): isPalindrome = False break p1 = p1.next p2 = p2.next return isPalindrome myLinkedList = LinkedList() myLinkedList.append(1) myLinkedList.append(3) myLinkedList.append(7) myLinkedList.append(7) myLinkedList.append(3) myLinkedList.append(1) print(linkedListPalindrome(myLinkedList)) print(linkedListPalindromeTwo(myLinkedList))
while temp.next is not None: temp = temp.next temp.next = pivot pivot.next = listB return listA else: return head if __name__ == '__main__': ll = LinkedList() ll_sort = SortLinkedList() ll.append(156) ll.append(4345) ll.append(45) ll.append(455) ll.push(10) ll.push(2060) ll.push(30) print("Unsorted: ") ll.printList() #h = ll_sort.mergeSort(ll.getHead()) h = ll_sort.quickSort(ll.getHead()) print("Sorted: ") ll.printList(h)
class OrderedSequenceAsLinkedList(OrderedSequence): """ Ordered sequence implemented using a linked list. """ __slots__ = ['__list'] def __init__(self): """ (OrderedSequenceAsLinkedList) -> None Constructs an ordered sequence. """ super(OrderedSequenceAsLinkedList, self).__init__() self.__list = LinkedList() self.count = 0 def insert(self, obj): """ (OrderedSequenceAsLinkedList, Object) -> None Inserts the given object at the end of this sequence. """ self.__list.append(obj) self.count +=1 def __getitem__(self, offset): """ (OrderedSequenceAsLinkedList, int) -> Object Returns the object in this sequence at the given offset. """ counter = 0 if offset < 0: raise IndexError() else: temp = self.__list.head while temp is not None: if counter is offset: return temp.data counter += 1 temp = temp.next if offset > counter: raise IndexError() def purge(self): """ (OrderedSequenceAsLinkedList) -> None Purges this ordered sequence. """ self.__list = LinkedList() self.count = 0 def accept(self, visitor): """ (OrderedSequenceAsLinkedList, Visitor) -> None Makes the given visitor visit all the objects in this ordered sequence. """ 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 __contains__(self, obj): """ (OrderedSequenceAsLinkedList, Object) -> bool Returns true if the given object instance is in this ordered sequence. """ if self.__list.isEmpty is True: return False temp = self.__list.head while temp is not None: if temp.data is obj: return True temp = temp.next return False def find(self, arg): """ (OrderedSequenceAsLinkedList, Object) -> Object Finds an object in this ordered sequence that equals the given object. """ if self.__list.isEmpty: return None temp = self.__list.head while temp is not None: if temp.data is arg: return temp.data temp = temp.next return None def withdraw(self, obj): """ (OrderedSequenceAsLinkedList, Object) -> None Withdraws the given object instance from this ordered sequence. """ if self.__list.isEmpty is True: raise IndexError() else: self.__list.extract(obj) if self.count > 0: self.count -= 1 def findPosition(self, obj): """ (OrderedSequenceAsLinkedList, Object) -> OrderedSequenceAsLinkedList.Cursor Finds the position of an object in this sequence that equals the given object and returns a cursor that refers to that object. """ ptr = self.__list.head while ptr is not None: if ptr.data is obj: return self.Cursor(self,ptr) ptr = ptr.next return self.Cursor(None,None) class Cursor(Cursor): """ A cursor that refers to an object in an ordered list. """ __slots__ = ['__element'] def __init__(self, lis, element): """ (OrderedSequenceAsLinkedList.Cursor, OrderedSequenceAsLinkedList, LinkedList.Element) -> None Constructs a cursor that refers to the object in the given element of the given sequence. """ super(OrderedSequenceAsLinkedList.Cursor, self).__init__(lis) self.__element = element def getData(self): """ (OrderedSequenceAsLinkedList.Cursor) -> Object Returns the object to which this cursor refers. """ if self.__element is not None: return self.__element.getData() else: raise IndexError() def insertAfter(self, obj): """ (OrderedSequenceAsLinkedList.Cursor, Object) -> None Inserts the given object into the sequence after the object to which this cursor refers. """ if self.__element is None: raise IndexError self.__element.insertAfter(obj) self.__sequence.count += 1 def insertBefore(self, obj): """ (OrderedSequenceAsLinkedList.Cursor, Object) -> None Inserts the given object into the sequence before the object to which this cursor refers. """ if self.__element is None: raise IndexError self.__element.insertBefore(obj) self.__sequence.count += 1 def withdraw(self): """ (OrderedSequenceAsLinkedList.Cursor) -> None Withdraws from the sequence the object to which this cursor refers. """ if self.__element is None: raise IndexError() self.__sequence._OrderedSequenceAsLinkedList__list.extract(self.__element.data) self.__sequence.count -= 1 class Iterator(Iterator): """ Enumerates the items in an ordered sequence. """ __slots__ = ['__element'] def __init__(self, lis): """ (OrderedSequenceAsLinkedList.Iterator, OrderedSequenceAsLinkedList) -> None Constructs an iterator for the given sequence. """ super(OrderedSequenceAsLinkedList.Iterator, self).__init__(lis) self.__element = None def next(self): """ (OrderedSequenceAsLinkedList.Iterator) -> Object Returns the next element. """ if self.container.isEmpty: raise StopIteration() if self.__element is None: self.__element = self.container._OrderedSequenceAsLinkedList__list.head elif self.__element.next is None: self.__element = None raise StopIteration() else: self.__element = self.__element.next return self.__element.data def __iter__(self): """ (OrderedSequenceAsLinkedList) -> OrderedSequenceAsLinkedList.Iterator Returns an iterator for this ordered sequence. """ return self.Iterator(self) def _compareTo(self, obj): """ (OrderedSequenceAsLinkedList, OrderedSequenceAsLinkedList) -> int Compares this ordered list with the given ordered sequence. """ assert isinstance(self, obj.__class__) raise TypeError, 'Not Implemented' @staticmethod def main(*argv): "OrderedSequenceAsLinkedList test program." print OrderedSequenceAsLinkedList.main.__doc__ lis = OrderedSequenceAsLinkedList() OrderedSequence.test(lis) return 0
from linkedList import LinkedList from hashTable import HashTable def loopDetection(linkedList): myHashTable = HashTable() current = linkedList.head while (current.next): if (myHashTable.get(current)): return current else: myHashTable.put(current, current.value) current = current.next myLinkedList = LinkedList() myLinkedList.append('A') myLinkedList.append('B') myLinkedList.append('C') myLinkedList.append('D') p = myLinkedList.head while (p.next): p = p.next p.next = myLinkedList.head print(loopDetection(myLinkedList).value)
return sum def addLists(linkedList1, linkedList2): l1 = linkedList1.length() l2 = linkedList2.length() if (l1 > l2): for i in range(0, l1 - l2): linkedList2.prepend(0) elif (l2 > l1): for i in range(0, l2 - l1): linkedList1.prepend(0) sum = sumTwoListsTwo(linkedList1.head, linkedList2.head) sum.sum.prepend(sum.carry) return sum.sum myLinkedList1 = LinkedList(9) myLinkedList1.append(9) myLinkedList1.append(9) myLinkedList2 = LinkedList(9) myLinkedList2.append(9) myLinkedList2.append(9) myLinkedList2.append(7) myLinkedList2.append(6) addLists(myLinkedList1, myLinkedList2).print()
class NoiseProfiler: 'Basic denoiser wrapper for keeping store of the settings' 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") def drawOriginalVsNoiseAndSingal(self): self.threshold = self.extractRMSthresholdFromWindows( self.percentileLevel) self.extractSignalAndNoiseWindows(self.threshold) noiseData = self.getDataOrZeroFromPartialWindows( self.windows, self.noiseWindows) signalData = self.getDataOrZeroFromPartialWindows( self.windows, self.signalWindows) rmsEnvelope = self.getWindowsRMSasEnvelope() plt.figure(1) plt.subplot(211) plt.plot(self.x) plt.subplot(211) plt.plot(rmsEnvelope) plt.plot(-1 * rmsEnvelope) plt.subplot(212) plt.plot(signalData) plt.plot(noiseData) plt.show() # Generally in each iteration we return the current window plus what's missing from the past # except if we are at the last noise window: then we have to care for the # missing future windows def __getPredictedDataBetweenNoiseWindows(self, currentWindow, prevWindow, nextWindow): result = [] if prevWindow == None: # it's the first noise window, so return this (replicated enough # times) numberToFill = currentWindow.id + 1 for i in range(numberToFill): result.extend(currentWindow.data) elif nextWindow == None: # if we're missing some windows from the end, pad/duplicate nWindows = len(self.windows) numberToFill = nWindows - currentWindow.id for i in range(numberToFill): result.extend(currentWindow.data) else: # we are between two noise windows numberToFill = currentWindow.id - prevWindow.id # TODO make some for i in range(numberToFill): result.extend(currentWindow.data) return result def __getPredictedDataBetweenNoiseNodes(self, currNode, prevNode, nextNode): result = [] if prevNode == None: # it's the first noise window, so return this currentWindow = currNode.data numberToFill = currentWindow.id + 1 return result def __getWindowIndexInList(self, needle, haystack): pos = 0 for candidate in haystack: if candidate == needle: return pos pos += 1 return -1 def __getUpToNConsecutiveWindows(self, lastWindow, windowList, n): result = [] result.append windowIndex = self.__getWindowIndexInList(lastWindow, windowList) # def __circularPadWindow(self, window, windowList, times): def getNoiseOrZero(self): self.threshold = self.extractRMSthresholdFromWindows( self.percentileLevel) self.extractSignalAndNoiseWindows(self.threshold) noiseData = [] for noiseNode in self.noiseLinked.getAsList(): window = noiseNode.data if window == None: noiseData.extend(numpy.zeros(self.windowSamples)) else: noiseData.extend(window.data) return noiseData def __getNodesWindowData(self, nodes): data = [] for node in nodes: window = node.data data.extend(window.data) return data def __getNodeCircularPrediction(self, node, n): prevNode = node.getPrevWithValidData() nextNode = node.getNextWithValidData() if prevNode == None: # work with current->future period of silence return self.__getFutureCircularNodes(nextNode, n) # working with the previous period of silence return self.__getPastCircularNodes(prevNode, n) def __getFutureCircularNodes(self, initialNode, n): ret = [] count = 0 current = initialNode while True: ret.append(current) count += 1 if count == n: return ret if current.next and current.next.data: current = current.next else: current = initialNode def __getPastCircularNodes(self, initialNode, n): ret = [] count = 0 current = initialNode while True: ret.append(current) count += 1 if count == n: return ret if current.prev and current.prev.data: current = current.prev else: current = initialNode def getNoiseDataPredicted(self): self.threshold = self.extractRMSthresholdFromWindows( self.percentileLevel) self.extractSignalAndNoiseWindows(self.threshold) noiseDataPredicted = [] consecutiveEmptyNodes = 0 lastValidNode = None for node in self.noiseLinked.getAsList(): if node.data == None: consecutiveEmptyNodes += 1 else: lastValidNode = node if consecutiveEmptyNodes != 0: predictedNodes = self.__getNodeCircularPrediction( node, consecutiveEmptyNodes) noiseDataPredicted.extend( self.__getNodesWindowData(predictedNodes)) consecutiveEmptyNodes = 0 window = node.data noiseDataPredicted.extend(window.data) # in case we had empty data on the end if consecutiveEmptyNodes != 0: predictedNodes = self.__getNodeCircularPrediction( lastValidNode, consecutiveEmptyNodes) noiseDataPredicted.extend( self.__getNodesWindowData(predictedNodes)) return noiseDataPredicted def __getPreviousNoiseWindowFromLinkedList(self, node): prevNode = node.getPrevWithValidData() if prevNode != None: return prevNode.data return None def __getNextNoiseWindowFromLinkedList(self, node): nextNode = node.getNextWithValidData() if nextNode != None: return nextNode.data return None def extractRMSthresholdFromWindows(self, percentileLevel): if self.threshold != None: return self.threshold sortedWindows = sorted(self.windows, key=lambda x: x.getRMS(), reverse=True) # now the are arranged with the max DESC nWindows = len(sortedWindows) thresholdIndex = math.floor(percentileLevel / 100 * nWindows) self.threshold = sortedWindows[thresholdIndex].getRMS() return self.threshold def getWindowsRMSasEnvelope(self): envelope = numpy.array([]) """ :type self.windows: list[windowBundle] """ for window in self.windows: windowEnvelope = window.getRMS() * numpy.ones(len(window.data)) envelope = numpy.concatenate([envelope, windowEnvelope]) return envelope def extractWindows(self): xLength = len(self.x) nWindows = math.ceil(xLength / self.windowSamples) lastWindowPaddingSamples = xLength - nWindows * self.windowSamples for i in range(0, nWindows): windowBeginning = i * self.windowSamples windowEnd = windowBeginning + self.windowSamples windowData = self.x[windowBeginning:windowEnd] # checking wether we need to pad the last band if (i == nWindows - 1 and windowEnd - windowBeginning < self.windowSamples): paddingLength = windowEnd - windowBeginning - self.windowSamples paddingArray = numpy.zeros(paddingLength) windowData = numpy.concatenate(windowData, paddingArray) window = windowBundle.WindowBundle(windowData, i) self.windows.append(window) def extractSignalAndNoiseWindows(self, rmsThreshold): if self.noiseWindows != None and self.signalWindows != None: return self.noiseWindows = list() self.signalWindows = list() for window in self.windows: # giving a +5% grace on the rms threshold comparison if window.getRMS() < (rmsThreshold + 0.05 * rmsThreshold): self.noiseWindows.append(window) self.noiseLinked.append(window) self.signalLinked.append(None) else: self.signalWindows.append(window) self.signalLinked.append(window) self.noiseLinked.append(None) def getDataOrZeroFromPartialWindows(self, allWindows, partialWindows): data = [] idx = 0 for window in allWindows: if idx < len(partialWindows) and window == partialWindows[idx]: data.extend(window.data) idx += 1 else: data.extend(numpy.zeros(self.windowSamples)) return data def extractWavelets(self): for window in self.windows: window.extractWaveletPacket(self.dbName, self.wlevels) def plotWavelets(self): wtBandsLength = 0 for window in self.windows: windowWaveletData = list() windowDataLength = 0 data = window.getData() wt = window.extractWaveletPacket(self.dbName, self.wlevels) leafNodes = [ node.path for node in wt.get_level(self.wlevels, 'freq') ] for node in leafNodes: bandData = wt[node].data windowWaveletData.extend(bandData) wtBandsLength += len(bandData) windowDataLength += len(bandData) print("window # " + str(window.id) + " of " + str(len(self.windows))) plt.figure(window.id) plt.subplot(211) plt.plot(window.data) plt.subplot(212) plt.plot(waveletHelper.waveletLeafData(window.waveletPacket)) plt.show()
from linkedList import LinkedList def deleteMiddleNode(linkedList, node): current = linkedList.head if (current.value == node): return linkedList while (current.next): if (current.next.value == node and current.next.next != None): current.next = current.next.next break elif (current.next.value == node and current.next.next == None): return linkedList current = current.next return linkedList myLinkedList = LinkedList(1) myLinkedList.append(5) myLinkedList.append(6) myLinkedList.append(7) myLinkedList.append(8) myLinkedList.append(9) deleteMiddleNode(myLinkedList, 8).print()
# Given two linked lists, the task is to check whether the first list is present in 2nd list or not. #http://www.geeksforgeeks.org/sublist-search-search-a-linked-list-in-another-list/ from linkedList import Node, LinkedList l1 = LinkedList() l1.append(1) l1.append(2) l1.append(3) l1.append(4) l2 = LinkedList() l2.append(1) l2.append(2) l2.append(1) l2.append(1) l2.append(2) l2.append(3) l2.append(4) # print l1.length() # if l1.head: # print 2 def subLinkedListSearch(l1, l2): # take the head nodes for both first = l1.head second = l2.head if l1.length() > l2.length():
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)
linkedList.head.value = arr[i] else: current.value = arr[i] current = current.next return linkedList def partitionTwo(linkedList, value): myLinkedList = LinkedList(None) current = linkedList.head while (current): if (current.value < value): myLinkedList.prepend(current.value) elif (current.value >= value): myLinkedList.append(current.value) current = current.next current = None return myLinkedList myLinkedList = LinkedList(3) myLinkedList.append(5) myLinkedList.append(8) myLinkedList.append(5) myLinkedList.append(10) myLinkedList.append(2) myLinkedList.append(1) myLinkedList.append(99) partition(myLinkedList, 5).print() partitionTwo(myLinkedList, 5).print()
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) myLinkedList.append(5)
from linkedList import LinkedList first = LinkedList() second = LinkedList() first.append(7) first.append(1) first.append(6) second.append(5) second.append(9) second.append(5) second.append(9) 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
from linkedList import LinkedList if __name__ == "__main__": print "Created list:" list = LinkedList([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) list.printList() print "length is:%d" % (list.getCount()) print "Deleting Node 5..." list.delNode(5) list.printList() print "Appending Node 5..." list.append(5) list.printList() print "del node at pos Node 4..." list.delNodeAt(4) list.printList() print "is 6 in list:%r" % (list.isInList(6)) print "is 11 in list:%r" % (list.isInList(11)) print "3rd last is:%d" % list.getKthLast(3) list.printList() print "Deleting mid" list.delNodeMid() # list.delNodeMid2(list.head.next.next) list.printList()