class LinkedListStack: # 비어있는 양방향 리스트로 초기화 def __init__(self): self.data = DoublyLinkedList() # 스택의 크기 반환 def size(self): return self.data.getLength() # 스택이 비어있는지 확인 def isEmpty(self): return self.size() == 0 # 스택에 데이터 추가 def push(self, item): # 노드를 새로 만듬 node = Node(item) # 마지막 자리에 데이터를 넣게 된다 self.data.insertAt(self.size() + 1, node) # 스택에 데이터 삭제 후 반환 def pop(self): return self.data.popAt(self.size()) # 스택의 맨 꼭대기의 데이터 반환 def peek(self): return self.data.getAt(self.size()).data
def mergeTwoSortedLists(l1, l2): if not l1: return l2 if not l2: return l1 if not l1 and not l2: return None ll = DoublyLinkedList() cur_l1 = l1.head cur_l2 = l2.head index = 0 max_length = l1.length + l2.length while index < max_length: if cur_l1 and cur_l2: if cur_l1.value <= cur_l2.value: ll.addAtIndex(index, cur_l1.value) cur_l1 = cur_l1.next else: ll.addAtIndex(index, cur_l2.value) cur_l2 = cur_l2.next elif cur_l1 and not cur_l2: ll.addAtIndex(index, cur_l1.value) cur_l1 = cur_l1.next elif cur_l2 and not cur_l1: ll.addAtIndex(index, cur_l2.value) cur_l2 = cur_l2.next index += 1 return ll
class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.firstIn = None self.storage = DoublyLinkedList() def append(self, item): if self.capacity > self.storage.length: self.storage.add_to_tail(item) if self.storage.length == 1: self.firstIn = self.storage.head else: self.firstIn.value = item if self.firstIn != self.storage.tail: self.firstIn = self.firstIn.next else: self.firstIn = self.storage.head def get(self): ringBufferList = [] node = self.storage.head while node != None: ringBufferList.append(node.value) node = node.next return ringBufferList
def test_unshift(self): """ Tests the unshift(data) method """ # test empty list dll = DoublyLinkedList() self.assertEqual(dll.length, 0) self.assertIsNone(dll.head) self.assertIsNone(dll.tail) dll.unshift('node zero') self.assertEqual(dll.length, 1) self.assertEqual(dll.head.data, 'node zero') # test one node expected_list = ['node zero'] self.assertEqual(dll.to_list(), expected_list) unshifted = dll.unshift('node subzero') self.assertIsInstance(unshifted, DoublyLinkedList) self.assertEqual(dll.length, 2) expected_list = ['node subzero', 'node zero'] self.assertEqual(dll.to_list(), expected_list) # test with two nodes unshifted = dll.unshift('node subsubzero') self.assertIsInstance(unshifted, DoublyLinkedList) self.assertEqual(dll.length, 3) expected_list = ['node subsubzero', 'node subzero', 'node zero'] self.assertEqual(dll.to_list(), expected_list)
class Queue: def __init__(self): self._list = DoublyLinkedList() self._size = 0 def getSize(self): return len(self._list) def enqueue(self,item): self._list.insertFront(item) def dequeue(self): return self._list.removeEnd() def __str__(self): return self._list.displayForward()
class LruCache(): def __init__(self, itemLimit): self.itemLimit = itemLimit self.itemCount = 0 self.store = {} self.list = DoublyLinkedList() def set(self, key, val): if key not in self.store: self.store[key] = Node(key, val) self.itemCount += 1 elif self.store.get(key) != val: self.store[key] = Node(key, val) self.list.addToHead(self.store.get(key)) if self.itemCount > self.itemLimit: tail = self.list.removeTail() del self.store[tail.key] def get(self, key): if key in self.store: node = self.store.get(key) self.list.moveToHead(node) return node.val def remove(self, key): if key in self.store: node = self.store.get(key) self.list.remove(node) del self.store[node.key] return node.val
def test_list_init(self): """ Test new DoublyLinked List initialization """ dll = DoublyLinkedList() self.assertIsInstance(dll, DoublyLinkedList) self.assertEqual(dll.length, 0) self.assertIsNone(dll.head) self.assertIsNone(dll.tail)
class LinkedListQueue: def __init__(self): self.data = DoublyLinkedList() def size(self): return self.data.nodeCount def isEmpty(self): return self.data.nodeCount == 0 def enqueue(self, item): node = Node(item) self.data.insertAt(self.size() + 1, node) def dequeue(self): return self.data.popAt(1) def peek(self): return self.data.head.next.data
def addingTwoNumbers(l1, l2): l1_values = [] l2_values = [] while l1.head or l2.head: if l1.head: l1_values.append(str(l1.head.value)) l1.head = l1.head.next if l2.head: l2_values.append(str(l2.head.value)) l2.head = l2.head.next sum_result = int("".join(l1_values[::-1])) + int("".join(l2_values[::-1])) sum_result = list(str(sum_result)) ll = DoublyLinkedList() index = 0 for i in range(len(sum_result) - 1, -1, -1): ll.addAtIndex(index, sum_result[i]) index += 1 return ll
def test_clear(self): """ Tests the clear() method """ dll = DoublyLinkedList() dll.push('node one') dll.push('node two') dll.push('node three') self.assertEqual(dll.length, 3) self.assertIsInstance(dll.clear(), DoublyLinkedList) self.assertEqual(dll.length, 0) self.assertIsNone(dll.head) self.assertIsNone(dll.tail)
class Deque(Container): def __init__(self): self._list = DoublyLinkedList() def getHead(self): return self._list.head def getTail(self): return self._list.tail head = property( fget = lambda self: self.getHead()) tail = property( fget = lambda self: self.getTail()) def enqueueHead(self, obj): self._list.prepend(obj) def dequeueHead(self): assert not self._list.isEmpty return self._list.extract(self._list.head.value) def enqueueTail(self, obj): self._list.append(obj) def dequeueTail(self): assert not self._list.isEmpty return self._list.extract(self._list.tail.value) def __iter__(self): pass def _compareTo(self, obj): pass def purge(self): self._list.purge() #override def getIsEmpty(self): return self._list.isEmpty
class Deque(Container): def __init__(self): self._list = DoublyLinkedList() def getHead(self): return self._list.head def getTail(self): return self._list.tail head = property(fget=lambda self: self.getHead()) tail = property(fget=lambda self: self.getTail()) def enqueueHead(self, obj): self._list.prepend(obj) def dequeueHead(self): assert not self._list.isEmpty return self._list.extract(self._list.head.value) def enqueueTail(self, obj): self._list.append(obj) def dequeueTail(self): assert not self._list.isEmpty return self._list.extract(self._list.tail.value) def __iter__(self): pass def _compareTo(self, obj): pass def purge(self): self._list.purge() #override def getIsEmpty(self): return self._list.isEmpty
class PriorityQueue: # 양방향 연결리스트를 이용하여 빈 큐를 초기화 def __init__(self, x): self.queue = DoublyLinkedList() # 크기를 반환 def size(self): return self.queue.getLength() # 비어있는가? def isEmpty(self): return self.size() == 0 # 데이터 삽입 연산 def enqueue(self, x): newNode = Node(x) # 처음 시작하는 위치 head에서 시작 curr = self.queue.head # 끝까지 가지 않을 조건 && 우선순위를 비교하는 조건 while curr.next != self.queue.tail and x < curr.next.data: curr = curr.next # 양방향 연결리스트를 이용해 삽입! self.queue.insertAfter(curr, newNode) # [주의] 양방향 연결리스트의 getAt()메서드를 이용하지 않는다. # why? # 데이터 삭제 연산 def dequeue(self): return self.queue.popAt(self.queue.getLength()) # 첫번째 데이터 반환 def peek(self): return self.queue.getAt(self.queue.getLength()).data
def test_push(self): """ Tests the push(data) method """ dll = DoublyLinkedList() dll.push('node zero') self.assertEqual(dll.length, 1) self.assertIsNotNone(dll.head) self.assertIsNotNone(dll.tail) self.assertIsNone(dll.head.next) self.assertIsNone(dll.head.prev) self.assertIsNone(dll.tail.prev) self.assertIsNone(dll.tail.next) self.assertEqual(dll.head.data, 'node zero') self.assertEqual(dll.tail.data, 'node zero') dll.push('node one') self.assertEqual(dll.length, 2) self.assertIsNone(dll.head.prev) self.assertIsNone(dll.tail.next) self.assertEqual(dll.head.data, 'node zero') self.assertEqual(dll.tail.data, 'node one') self.assertEqual(dll.head.next.data, 'node one') self.assertEqual(dll.tail.prev.data, 'node zero')
def setUp(self): self.list = DoublyLinkedList()
if cur_l1.value <= cur_l2.value: ll.addAtIndex(index, cur_l1.value) cur_l1 = cur_l1.next else: ll.addAtIndex(index, cur_l2.value) cur_l2 = cur_l2.next elif cur_l1 and not cur_l2: ll.addAtIndex(index, cur_l1.value) cur_l1 = cur_l1.next elif cur_l2 and not cur_l1: ll.addAtIndex(index, cur_l2.value) cur_l2 = cur_l2.next index += 1 return ll if __name__ == "__main__": LL1 = DoublyLinkedList() LL1.addAtHead(1) LL1.addAtTail(2) LL1.addAtTail(4) print(LL1) LL2 = DoublyLinkedList() LL2.addAtHead(1) LL2.addAtTail(3) LL2.addAtTail(4) print(LL2) print(mergeTwoSortedLists(LL1, LL2))
l2_values.append(str(l2.head.value)) l2.head = l2.head.next sum_result = int("".join(l1_values[::-1])) + int("".join(l2_values[::-1])) sum_result = list(str(sum_result)) ll = DoublyLinkedList() index = 0 for i in range(len(sum_result) - 1, -1, -1): ll.addAtIndex(index, sum_result[i]) index += 1 return ll if __name__ == "__main__": LL1 = DoublyLinkedList() LL1.addAtHead(2) LL1.addAtTail(4) LL1.addAtTail(9) print(LL1) LL2 = DoublyLinkedList() LL2.addAtHead(5) LL2.addAtTail(6) LL2.addAtTail(4) LL2.addAtTail(9) print(LL2) print(addingTwoNumbers(LL1, LL2)) LL3 = DoublyLinkedList()
from Node import Node from doublyLinkedList import DoublyLinkedList # node1 = Node(1) # node2 = Node(2) dl = DoublyLinkedList() dl.insertAtBeginning(4) dl.insertAtBeginning(5) dl.insertAtEnd(6) dl.insertAtPos(8, 2) dl.printList() # dl.deleteFirstNode() dl.deleteLastNode # dl.insertAtBeginning(7) # dl.insertAtBeginning(9) # dl.insertAtPos(10,3) # dl.insertAtPos(11,0) # dl.deleteFirstNode() # dl.deleteLastNode() dl.deleteFromPos(2) # dl.deleteFromPos(2) # dl.deleteFromPos(3) dl.printList()
def test_pop(self): """ Tests the pop() method """ dll = DoublyLinkedList() # test with no nodes self.assertIsNone(dll.pop()) # test with one node dll.push('node zero') self.assertEqual(dll.length, 1) popped = dll.pop() self.assertEqual(dll.length, 0) self.assertEqual(popped.data, "node zero") # test with two nodes dll.push('node zero') dll.push('node one') self.assertEqual(dll.head.data, 'node zero') self.assertEqual(dll.tail.data, 'node one') self.assertEqual(dll.length, 2) popped = dll.pop() self.assertEqual(popped.data, 'node one') self.assertEqual(dll.length, 1) # test pop prev, next are None self.assertIsNone(popped.prev) self.assertIsNone(popped.next)
def main(): # Start with empty list llist = DoublyLinkedList() # Insert 6. So the list becomes 6->None llist.append(6) # Insert 7 at the beginning. # So linked list becomes 7->6->None llist.push(7) # Insert 1 at the beginning. # So linked list becomes 1->7->6->None llist.push(1) # Insert 4 at the end. # So linked list becomes 1->7->6->4->None llist.append(4) # Insert 8, after 7. # So linked list becomes 1->7->8->6->4->None llist.insert(llist.head.next, 8) print('###################') llist.printList() # So linked list becomes 1->7->8->2->6->4->None llist.insertAt(2, 2) llist.printList() print('###################') llist.delete(llist.head) llist.delete(llist.head.next) llist.delete(llist.head.next) llist.printList() print('###################') llist.deleteAt(2) llist.printList()
def __init__(self): self._list = DoublyLinkedList()
def test_to_list(self): """ Tests the to_list() method """ dll = DoublyLinkedList() self.assertEqual(dll.to_list(), [])
def __init__(self, capacity): self.capacity = capacity self.firstIn = None self.storage = DoublyLinkedList()
def __init__(self, itemLimit): self.itemLimit = itemLimit self.itemCount = 0 self.store = {} self.list = DoublyLinkedList()
def __init__(self): self.data = DoublyLinkedList()
def test_shift(self): """ Tests the shift() method """ dll = DoublyLinkedList() # test shifting empty list self.assertIsNone(dll.shift()) # test one node dll.push('node zero') self.assertEqual(dll.length, 1) shifted = dll.shift() self.assertEqual(dll.length, 0) self.assertIsNone(dll.head) self.assertIsNone(dll.tail) self.assertEqual(shifted.data, 'node zero') self.assertIsNone(shifted.next) self.assertIsNone(shifted.prev) # test two nodes dll.push('node one') dll.push('node two') self.assertEqual(dll.length, 2) shifted = dll.shift() self.assertEqual(dll.length, 1) expected_list = ['node two'] self.assertEqual(dll.to_list(), expected_list) self.assertIsNone(shifted.next) self.assertIsNone(shifted.prev) # test three nodes dll = DoublyLinkedList() dll.push('node one') dll.push('node two') dll.push('node three') self.assertEqual(dll.length, 3) shifted = dll.shift() self.assertEqual(dll.length, 2) expected_list = ['node two', 'node three'] self.assertEqual(dll.to_list(), expected_list) self.assertIsNone(shifted.next) self.assertIsNone(shifted.prev)
def test_get(self): """ Tests the get(index) method """ dll = DoublyLinkedList() dll.push(0) # index 0 dll.push(1) # index 1 dll.push(2) # index 2 dll.push(3) # index 3 dll.push(4) # index 4 dll.push(5) # index 5 self.assertEqual(dll.length, 6) # test out of bounds self.assertIsNone(dll.get(-1)) self.assertIsNone(dll.get(99)) self.assertIsNone(dll.get(6)) self.assertEqual(dll.get(0).data, 0) self.assertEqual(dll.get(3).data, 3) self.assertEqual(dll.get(4).data, 4) self.assertEqual(dll.get(5).data, 5)
def setUp(self): self.l = DoublyLinkedList()
def test_set(self): """ Tests the set(index, data) method """ dll = DoublyLinkedList() # test empty list self.assertIsNone(dll.set(0, 'data')) # test out of bounds self.assertIsNone(dll.set(-1, 'data')) self.assertIsNone(dll.set(1, 'data')) dll.push(0) # index 0 dll.push(1) # index 1 dll.push(2) # index 2 dll.push(3) # index 3 dll.push(4) # index 4 dll.push(5) # index 5 self.assertEqual(dll.length, 6) self.assertIsInstance(dll.set(2, "index 2"), Node) expected_list = [0, 1, 'index 2', 3, 4, 5] self.assertEqual(dll.to_list(), expected_list)
def test_insert(self): """ Tests the insert(index, data) method """ dll = DoublyLinkedList() # test out of bounds self.assertIsNone(dll.insert(-1, 'data')) self.assertIsNone(dll.insert(1, 'data')) # test inserting at index zero in open list (should use unshift(data)) dll.insert(0, 'node zero') self.assertEqual(dll.length, 1) self.assertEqual(dll.head.data, 'node zero') dll.clear() dll.push(0) # index 0 dll.push(1) # index 1 dll.push(2) # index 2 # insert at index 1 expected_list = [0, 'insert one', 1, 2] self.assertIsInstance(dll.insert(1, 'insert one'), DoublyLinkedList) self.assertEqual(dll.length, 4) self.assertEqual(dll.to_list(), expected_list) # insert at tail, index 4 expected_list = [0, 'insert one', 1, 2, 'insert tail'] self.assertIsInstance(dll.insert(4, 'insert tail'), DoublyLinkedList) self.assertEqual(dll.length, 5) self.assertEqual(dll.to_list(), expected_list)
class DoublyLinkedListTest(unittest.TestCase): def setUp(self): self.list = DoublyLinkedList() def test_addFirst(self): self.list.addFirst(1) self.list.addFirst(2) self.list.addFirst(3) self.list.addFirst(4) self.assertEqual('4,3,2,1', self.list.toString()) def test_addLast(self): self.list.addLast(1) self.list.addLast(2) self.list.addLast(3) self.list.addLast(4) self.assertEqual('1,2,3,4', self.list.toString()) def test_addFront(self): self.list.addFront(1, 0) self.list.addFront(2, 0) self.list.addFront(3, 1) self.list.addFront(4, 2) self.list.addFront(5, 2) self.list.addFront(6, 3) self.assertEqual('2,3,5,6,4,1', self.list.toString()) def test_addBack(self): self.list.addBack(1, 0) self.list.addBack(2, 1) self.list.addBack(3, 1) self.list.addBack(4, 1) self.assertEqual('1,2,4,3', self.list.toString()) def _getNodes(self): self.list.addLast(1) self.list.addLast(2) self.list.addLast(3) self.list.addLast(4) self.list.addLast(5) def test_removeFirst(self): self._getNodes() self.assertEqual(1, self.list.removeFirst()) self.assertEqual(2, self.list.removeFirst()) self.assertEqual(3, self.list.removeFirst()) self.assertEqual(4, self.list.removeFirst()) self.assertEqual(5, self.list.removeFirst()) self.assertIsNone(self.list.removeFirst()) self._getNodes() self.list.removeFirst() self.list.removeFirst() self.list.addFirst(6) self.list.addBack(7, 2) self.list.removeFirst() self.list.addFront(8, 3) self.list.addLast(9) self.assertEqual('3,4,7,8,5,9', self.list.toString()) def test_remove(self): self._getNodes() self.assertIsNone(self.list.remove(5)) self.assertIsNone(self.list.remove(-1)) self.assertEqual(5, self.list.remove(4)) self.assertEqual(1, self.list.remove(0)) self.assertEqual(3, self.list.remove(1)) self.assertEqual(4, self.list.remove(1)) self.assertEqual(2, self.list.remove(0)) def test_removeLast(self): self._getNodes() self.assertEqual(5, self.list.removeLast()) self.assertEqual(4, self.list.removeLast()) self.assertEqual(3, self.list.removeLast()) self.assertEqual(2, self.list.removeLast()) self.assertEqual(1, self.list.removeLast()) self.assertIsNone(self.list.removeLast()) def test_empty(self): self.assertEqual(True, self.list.empty()) self.list.addFirst(1) self.assertEqual(False, self.list.empty()) def test_size(self): self.assertEqual(0, self.list.size()) self.list.addBack(1, 1) self.list.addFirst(2) self.list.addLast(3) self.list.removeFirst() self.list.addFront(4, 2) self.list.addFirst(5) self.list.removeLast() self.list.addLast(6) self.list.addLast(7) self.list.addLast(8) self.list.remove(3) self.assertEqual('5,1,3,7,8', self.list.toString()) self.assertEqual(5, self.list.size()) def test_get(self): self._getNodes() self.assertIsNone(self.list.get(-1)) self.assertEqual(1, self.list.get(0)) self.assertEqual(2, self.list.get(1)) self.assertEqual(3, self.list.get(2)) self.assertEqual(4, self.list.get(3)) self.assertEqual(5, self.list.get(4)) self.assertIsNone(self.list.get(5)) def test_indexOf(self): self._getNodes() self.assertEqual(0, self.list.indexOf(1)) self.assertEqual(1, self.list.indexOf(2)) self.assertEqual(2, self.list.indexOf(3)) self.assertEqual(3, self.list.indexOf(4)) self.assertEqual(4, self.list.indexOf(5)) self.assertEqual(-1, self.list.indexOf(6))
def test_delete(self): """ tests the delete(index) method """ dll = DoublyLinkedList() # test out of bounds self.assertIsNone(dll.delete(-1)) self.assertIsNone(dll.delete(1)) dll.push(0) # index 0 dll.push(1) # index 1 dll.push(2) # index 2 # test can delete head (index 0) deleted = dll.delete(0) self.assertIsInstance(deleted, Node) self.assertEqual(deleted.data, 0) self.assertEqual(dll.length, 2) # unshift the node back, then test delete at tail (index 2) dll.unshift(0) self.assertEqual(dll.to_list(), [0, 1, 2]) self.assertEqual(dll.length, 3) deleted = dll.delete(dll.length - 1) # index 2 self.assertIsInstance(deleted, Node) self.assertEqual(deleted.data, 2) self.assertEqual(dll.length, 2) # push the node back, then test delete from middle (index 1) dll.push(2) self.assertEqual(dll.to_list(), [0, 1, 2]) self.assertEqual(dll.length, 3) deleted = dll.delete(1) self.assertIsInstance(deleted, Node) self.assertEqual(deleted.data, 1) self.assertEqual(dll.length, 2)
def main(): print('###############################') # array declaration arr = [2, 3, 5, 8, 9, 10, 11] # value to search val = 17 print(isPairSum(arr, len(arr), val)) print('###############################') llist = DoublyLinkedList() for item in arr: llist.append(item) pairSum( llist.head, val ) print('###############################') arr = [0, -1, 2, -3, 1] n = len(arr) findTriplets_hash(arr, n) print('###############################') findTriplets(arr, n) print('###############################') nums = [0,0,1,1,1,2,2,3,3,4] k = removeDuplicates( nums ) print(k) print(nums[:k]) nums = [1,1,2] k = removeDuplicates( nums ) print(k) print(nums[:k]) nums = [0,0,1,1,1,2,2,3,3,4] print('######## removeDuplicates2 #######################') k = removeDuplicates2( nums ) print(k) print(nums[:k]) print('###############################') llist = LinkedList() llist.push(20) llist.push(4) llist.push(4) llist.push(20) print( isPalindrome(llist.head) ) print( isPalindrome2(llist.head) ) print('###############################') llist = LinkedList() llist.push(7) llist.push(6) llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) llist.printList() print('###############################') reorderList(llist.head) llist.printList() print('###############################') arr = [1,2,3,4,5,6] swap(arr,0,3) print(arr) reverse(arr) print(arr) print('###############################') height = [1,8,6,2,5,4,8,3,7] print(maxArea(height)) print('###############################')
class TestList(unittest.TestCase): def setUp(self): self.l = DoublyLinkedList() def test_init(self): self.assertEqual(self.l.head, None) self.assertEqual(self.l.tail, None) def test_append(self): self.l.append(1) self.assertEqual(self.l.head.value, 1) self.assertEqual(self.l.tail.value, 1) self.l.append(2) self.assertEqual(self.l.head.value, 1) self.assertEqual(self.l.tail.value, 2) self.assertEqual(self.l.first.value, 1) self.assertEqual(self.l.last.value, 2) def test_prepend(self): self.l.prepend(1) self.assertEqual(self.l.head.value, 1) self.assertEqual(self.l.tail.value, 1) self.l.prepend(2) self.assertEqual(self.l.head.value, 2) self.assertEqual(self.l.tail.value, 1) self.l.prepend(3) self.assertEqual(self.l.head.value, 3) self.assertEqual(self.l.tail.value, 1) def test_purge(self): self.l.append(1) self.l.append(2) self.l.append(3) self.assertEqual(self.l.head.value, 1) self.assertEqual(self.l.tail.value, 3) self.l.purge() self.assertEqual(self.l.head, None) self.assertEqual(self.l.tail, None) def test_extract(self): self.l.append(1) self.l.append(2) self.l.append(3) self.l.append(4) self.l.append(5) self.assertEqual(self.l.extract(1), 1) self.assertEqual(self.l.head.value, 2) self.assertEqual(self.l.extract(10), None) self.assertEqual(self.l.extract(5), 5) self.assertEqual(self.l.tail.value, 4) def test_copy(self): self.l.append(1) self.l.append(2) self.l.append(3) a = copy(self.l) self.assertEqual(a.head.value, 1) self.assertEqual(a.tail.value, 3) def test_empty(self): self.assertTrue(self.l.isEmpty) self.l.append(1) self.assertFalse(self.l.isEmpty) self.l.extract(1) self.assertTrue(self.l.isEmpty)