Example #1
0
class LinkedQueue(Queue):
    def __init__(self):
        self.list = DoublyLinkedList()
        self.iter_list = iter(self.list)

    def size(self):
        return self.list.size()

    def is_empty(self):
        return self.size() == 0

    def peek(self):
        if self.isEmpty():
            raise Exception('Queue Empty')
        return self.list.peek_first()

    def poll(self):
        ''' poll from front of queue '''
        if self.isEmpty():
            raise Exception('Queue Empty')
        return self.list.remove_head()

    def offer(self, elem):
        ''' add elem to back of queue '''
        self.list.append(elem)

    def __iter__(self):
        ''' called when iteration is initialized '''
        self.iter_list = iter(self.list)
        return self

    def __next__(self):
        ''' To move to next element '''
        return next(self.iter_list)
 def test_add_before_node(self):
     llist = DoublyLinkedList()
     llist.append('A')
     llist.append('B')
     llist.append('D')
     llist.add_before_node('D', 'C')
     self.assertEqual(repr(llist), 'A, B, C, D')
Example #3
0
def test_dll():
    test_dll = Dll()
    test_dll.insert('test1')
    test_dll.insert('test2')
    test_dll.append('test3')

    return test_dll
Example #4
0
class Heap:
    def __init__(self):
        self.storage = DoublyLinkedList()

    def insert(self, value):
        self.storage.append(value)
        self._bubble_up(len(self.storage) - 1)

    def delete(self):
        value = self.storage[0]
        if len(self.storage) > 1:
            self.storage[0] = self.storage.remove_from_tail()
        elif len(self.storage) == 1:
            self.storage.remove_from_tail()
        self._sift_down(0)
        return value

    def get_max(self):
        return self.storage[0]

    def __len__(self):
        return len(self.storage)

    get_size = __len__

    def _swap(self, index_0, index_1):
        (
            self.storage[index_0],
            self.storage[index_1],
        ) = (
            self.storage[index_1],
            self.storage[index_0],
        )

    def _bubble_up(self, index):
        parent_index = (index - 1) // 2
        if parent_index < 0:
            return
        # print(f'_bubble_up({index})')
        # print(self.storage)
        # print(f'index {index}: {self.storage[index]}')
        # print(f'parent_index {parent_index}: {self.storage[parent_index]}')
        if self.storage[index] > self.storage[parent_index]:
            self._swap(index, parent_index)
            self._bubble_up(parent_index)

    def _sift_down(self, index):
        child_values = list(self.storage[index * 2 + 1:index * 2 + 3])
        if len(child_values) == 0:
            return
        if self.storage[index] > max(child_values):
            return
        if len(child_values) == 1:
            self._swap(index * 2 + 1, index)
        elif child_values[0] >= child_values[1]:
            self._swap(index * 2 + 1, index)
            self._sift_down(index * 2 + 1)
        else:
            self._swap(index * 2 + 2, index)
            self._sift_down(index * 2 + 2)
Example #5
0
class Queue(object):
    """Class to create instance of Queue."""
    def __init__(self):
        """Create new instance of Queue class object."""
        self.queue = DoublyLinkedList()
        self.is_empty = True

    def enqueue(self, data):
        """Method to add given data to Queue class object."""
        if not self.queue.head:
            self.is_empty = False
        self.queue.append(data)

    def dequeue(self):
        """Method to remove and return item at front of Queue class object."""

        if not self.queue.head:
            raise IndexError('Cannot perform dequeue on empty Queue.')

        if not self.queue.head.next_node:
            self.is_empty = True

        return self.queue.pop()

    def peek_front(self):
        """Method to return item at front of Queue class object."""
        return self.queue.head

    def peek_back(self):
        """Method to return item at back of Queue class object."""
        return self.queue.tail
Example #6
0
def test_append_method_assigns_head_and_tail_to_be_same_node_if_list_empty():
    """Test that the append method of the DoublyLinkedList class correctly
    assigns the list's head and tail to be the same Node if append is used on
    an empty list."""

    dll = DoublyLinkedList()
    dll.append(1)

    assert dll.tail is dll.head
Example #7
0
def test_append_method_creates_instance_of_node_class_as_new_node():
    """Test that the append method of the DoublyLinkedList class adds an
    instance of the Node class as the new Node in the list."""

    dll = DoublyLinkedList()
    dll.add_node(1)

    dll.append(2)
    assert isinstance(dll.tail, Node)
Example #8
0
def test_append_method_correctly_reassigns_tail_to_newly_added_node():
    """Test that the append method of the DoublyLinkedList class correctly
    reassigns the list's tail to become the newly appended Node."""

    dll = DoublyLinkedList()
    dll.add_node(1)
    old_tail = dll.tail

    dll.append(2)
    assert dll.tail != old_tail and dll.tail.data != old_tail.data
Example #9
0
def test_append_method_assigns_new_tails_prev_node_to_be_old_tail():
    """Test that the append method of the DoublyLinkedList class assigns the
    new tail's prev_node pointer to be the old tail, preserving the integrity
    of the list."""

    dll = DoublyLinkedList()
    dll.add_node(10)
    old_tail = dll.tail

    dll.append(20)
    assert dll.tail.prev_node is old_tail
Example #10
0
def test_append_method_correctly_reassigns_tail_through_multiple_uses():
    """Test that the append method of the DoublyLinkedList class correctly
    reassigns the list's tail after multiple uses."""

    dll = DoublyLinkedList()
    dll.append(3)

    old_tail = dll.tail

    dll.append(6)
    dll.append(9)

    assert dll.tail is not old_tail
Example #11
0
def test_append_method_does_not_reassign_head_through_multiple_uses():
    """Test that the append method of the DoublyLinkedList class doesn't
    reassign the list's head after first use, even after multiple uses."""

    dll = DoublyLinkedList()
    dll.append(5)

    head = dll.head

    dll.append(10)
    dll.append(15)

    assert dll.head is head
    def test_doubly_linked_list_search(self):

        doubly_linked_list = DoublyLinkedList()
        doubly_linked_list.append(25)
        pos = doubly_linked_list.search(25)
        self.assertIsNotNone(doubly_linked_list)
        self.assertTrue(pos == 0)
        doubly_linked_list.append("Riccardo")
        pos = doubly_linked_list.search("Riccardo")
        self.assertEqual(pos,1)
        doubly_linked_list.insert_head("Prova")
        pos = doubly_linked_list.search("Prova")
        self.assertTrue(pos == 0)
Example #13
0
class Deque(object):
    """Deque object class."""

    def __init__(self):
        """Init new deque instance."""
        self._deque = DoublyLinkedList()

    def append(self, val):
        """Add item to right end of deque."""
        self._deque.append(val)

    def appendleft(self, val):
        """Add item to left end of deque."""
        self._deque.push(val)

    def pop(self):
        """Remove item from right end of deque."""
        try:
            return self._deque.shift()
        except IndexError:
            raise IndexError('Cannot pop from empty deque.')

    def popleft(self):
        """Remove item from head, left-side, of deque."""
        try:
            return self._deque.pop()
        except IndexError:
            raise IndexError('Cannot pop from empty deque')

    def peek(self):
        """Show data of item at back of deque."""
        try:
            return self._deque.tail.data
        except AttributeError:
            return None

    def peekleft(self):
        """Show data of item at front of deque."""
        try:
            return self._deque.head.data
        except AttributeError:
            return None

    def size(self):
        """Return the size of the deque."""
        return self._deque._len

    def __len__(self):
        """Return the size of the deque with len."""
        return len(self._deque)
Example #14
0
class Stack:
    def __init__(self):
        self.size = 0
        # Why is our DLL a good choice to store our elements?
        self.storage = DoublyLinkedList()

    def push(self, value):
        self.storage.append(value)

    def pop(self):
        return self.storage.pop()

    def len(self):
        return len(self.storage)
    def test_DoublyLinkedList_append(self):
        l1 = DoublyLinkedList()
        l1.append(0)

        # ensure Node(0) added to list
        Node0 = l1.head
        self.assertIsNotNone(l1.head)
        self.assertIsNotNone(l1.tail)
        self.assertEqual(Node0.val, 0)
        self.assertIsNone(Node0.link)

        # ensure Node(1) appended to back of list
        l1.append(1)
        Node0 = l1.head
        self.assertEqual(Node0.val, 0)
        self.assertIsNotNone(Node0.link)

        # ensure Node(0) is next in list
        Node1 = Node0.link
        self.assertEqual(Node1.val, 1)
        self.assertIsNone(Node1.link)

        # ensure adding 'None' adds something
        sz1 = l1.size()
        l1.append(None)
        self.assertEqual(sz1+1, l1.size())

        # ensure adding recursively adds nothing
        sz1 = l1.size()
        l1.append(l1)
        self.assertEqual(sz1, l1.size())
Example #16
0
class Deque(object):
    """Create a Deque object."""
    def __init__(self):
        """Initialize Deque using DoublyLinkedList methods."""
        self._doubly_linked_list = DoublyLinkedList()

    def append(self, val):
        """Add a node to back Deque."""
        self._doubly_linked_list.append(val)

    def appendleft(self, val):
        """Add a node to front Deque."""
        self._doubly_linked_list.push(val)

    def pop(self):
        """Remove node at the back."""
        try:
            return self._doubly_linked_list.shift()
        except IndexError:
            raise IndexError('Nothing to pop from back')

    def popleft(self):
        """Remove node at the front."""
        try:
            return self._doubly_linked_list.pop()
        except IndexError:
            raise IndexError('Nothing to pop from front')

    def peek(self):
        """Get value of next node to be popped left."""
        if self._doubly_linked_list.size() == 0:
            return None
        return self._doubly_linked_list.tail.data

    def peekleft(self):
        """Get value of next node to be popped."""
        if self._doubly_linked_list.size() == 0:
            return None
        return self._doubly_linked_list.head.data

    def size(self):
        """Get the size of the Deque."""
        return self._doubly_linked_list.size()

    def __len__(self):
        """Return the length of the Deque using Python len function."""
        return self.size()
    def test_delete_node(self):
        llist = DoublyLinkedList()
        llist.append('A')
        llist.append('B')
        llist.append('C')
        llist.append('D')
        llist.delete('C')
        self.assertEqual(repr(llist), 'A, B, D')

        # delete first node
        llist.delete('A')
        self.assertEqual(repr(llist), 'B, D')

        # delete last node
        llist.delete('D')
        self.assertEqual(repr(llist), 'B')

        # delete only node
        llist.delete('B')
Example #18
0
class RingBuffer:
	def __init__(self, capacity):
		self.capacity = capacity
		self.current = None
		self.storage = DoublyLinkedList()

	def append(self, item):
		if len(self.storage) < self.capacity:
			self.storage.append(item)
			self.current = len(self.storage) - 1
			return

		self.current += 1
		if self.current >= self.capacity:
			self.current = 0
		self.storage[self.current] = item

	def get(self):
		return list(self.storage)
Example #19
0
    def run(self, input_string):
        time1 = time.time()

        # convert the input to a  doubly linked list
        band = DoublyLinkedList()
        for letter in input_string:
            band.append(letter)

        tm_is_running = True

        while (tm_is_running):
            #print("current_bit ", band.get(self.current_bit))
            #print("current_state ", self.current_state)
            #print()

            # main loop
            for delta in self.delta_funcs:
                #print("delta ", delta)

                # find the delta function for the current symbol and current state
                if delta[0][0] == self.current_state and delta[0][1] == band.get(self.current_bit):
                    # set the new state
                    self.current_state = delta[1][0]
                    # set the new symbol
                    band.replace(self.current_bit, delta[1][1])
                    direction = delta[1][2]
                    if direction == "R":
                        self.current_bit += 1
                        if band.get(self.current_bit + 1) == None:
                            band.append(" ")
                    if direction == "L":
                        band.push(" ")
                        self.current_bit = 0
                    break

            # check if the current state is the accepting state
            if (self.current_state == self.accepting_state):
                tm_is_running = False
                time2 = time.time()
                print('accepted in %0.3f ms' % ((time2-time1) * 1000.0))
                return
Example #20
0
def test_doubly_linked_list_remove_end(N):
    print("Testing DoublyLinkedList")
    l = DoublyLinkedList()

    print(f"Appending {int(N)} values")
    [l.append(i) for i in range(int(N))]
    print(f"Removing {int(N)-10} values from the end")
    [l.remove_end() for i in range(int(N) - 10)]
    try:
        l.remove_end()
    except Exception:
        print("Got expected Exception")
Example #21
0
class Deque(object):
    """Deque data structure, can add and remove from both ends."""
    def __init__(self):
        """Initialize the deque."""
        self.deque = DoublyLinkedList()

    def append(self, value):
        """Add an item to the back of the deque."""
        self.deque.append(value)

    def appendleft(self, value):
        """Add an item to the front of the deque."""
        self.deque.push(value)

    def pop(self):
        """Pop a value off of the back of the deque and return it."""
        return self.deque.shift()

    def popleft(self):
        """Pop a value off of the front of the deque and return it."""
        return self.deque.pop()

    def peek(self):
        """Return the next value that would be poped at the end of deque."""
        try:
            return self.deque.tail.data
        except AttributeError:
            return None

    def peekleft(self):
        """Return the next value in the deque. This is the value that popleft would remove."""
        try:
            return self.deque.head.data
        except AttributeError:
            return None

    def size(self):
        """Return the number of nodes in the deque."""
        return self.deque.__len__()
    def test_doubly_linked_list_insert(self):

        doubly_linked_list = DoublyLinkedList()
        with self.assertRaises(ValueError):
            doubly_linked_list.insert(99, 5)
        print doubly_linked_list.append(25)
        print doubly_linked_list.append("Riccardo")
        print doubly_linked_list.append("Try")
        print doubly_linked_list.insert(6, 3)
        self.assertTrue(doubly_linked_list.tail.previous.item == "Try")
        self.assertEqual(doubly_linked_list.tail.next, None)
        self.assertTrue(doubly_linked_list.tail.item == 6)
    def test_doubly_linked_list_append(self):

        doubly_linked_list = DoublyLinkedList()
        doubly_linked_list.append(25)
        self.assertIsNotNone(doubly_linked_list)
        self.assertTrue(doubly_linked_list.__len__() == 1)
        doubly_linked_list.append("Riccardo")
        self.assertTrue(doubly_linked_list.__len__() == 2)
        self.assertTrue(doubly_linked_list.head.item == 25)
        self.assertTrue(doubly_linked_list.tail.item == "Riccardo")
        self.assertEqual(doubly_linked_list.tail.next, None)
        self.assertTrue(doubly_linked_list.head.next.item == "Riccardo")
        self.assertFalse(doubly_linked_list.head.next.item == "25")
        doubly_linked_list.append("Try")
        self.assertTrue(doubly_linked_list.head.item == 25)
        self.assertTrue(doubly_linked_list.head.next.item == "Riccardo")
        self.assertTrue(doubly_linked_list.tail.item == "Try")
        self.assertTrue(doubly_linked_list.head.next.item == "Riccardo")
        self.assertEqual(doubly_linked_list.tail.next, None)
    def test_doubly_linked_list_delete(self):

        doubly_linked_list = DoublyLinkedList()
        doubly_linked_list.append(25)
        doubly_linked_list.append("Riccardo")
        doubly_linked_list.append("Try")
        doubly_linked_list.insert(6, 3)
        self.assertIsNotNone(doubly_linked_list)
        self.assertTrue(doubly_linked_list.__len__() == 4)
        self.assertTrue(doubly_linked_list.tail.item == 6)
        doubly_linked_list.delete(3)
        self.assertTrue(doubly_linked_list.__len__() == 3)
        self.assertTrue(doubly_linked_list.tail.item == "Try")
        self.assertFalse(doubly_linked_list.tail.item == 6)
        self.assertTrue(doubly_linked_list.head.item == 25)
        self.assertFalse(doubly_linked_list.head.next.item == "Try")
        self.assertTrue(doubly_linked_list.head.next.item == "Riccardo")
        doubly_linked_list.delete(0)
        self.assertTrue(doubly_linked_list.head.item == "Riccardo")
        self.assertTrue(doubly_linked_list.head.next.item == "Try")
Example #25
0
def singly_palindrom(slist):
    head = slist.head
    vals = ""
    while head:
        vals += str(head.data)
        head = head.next
    if len(longestPalindrome(vals)) == len(vals):
        return True
    return False
        
    

if __name__ == "__main__":
#__________FOR DOUBLY LINKED LIST_______________
    dlist = DoublyLinkedList()
    dlist.append(1)
    dlist.append(2)
    dlist.append(3)
    dlist.append(2)
    dlist.append(1)
    assert doubly_palindrom(dlist) == True
    
    dlist = DoublyLinkedList()
    dlist.append(1)
    dlist.append(4)
    assert doubly_palindrom(dlist) == False
    
#__________FOR SINGLY LINKED LIST_______________
    slist = LinkedList()
    slist.append(1)
    slist.append(2)
Example #26
0
def get_instance():
    linked_list = DoublyLinkedList(Node(100))
    linked_list.append(Node(200))
    linked_list.append(Node(300))
    linked_list.append(Node(400))
    return linked_list
Example #27
0
def test_doubly_linked_list_append(N):
    print("Testing DoublyLinkedList")
    l = DoublyLinkedList()

    print(f"Appending {int(N)} values")
    [l.append(i) for i in range(int(N))]
Example #28
0
class TestDoublyLinkedList(unittest.TestCase):

	def setUp(self):
		self.emptyList = DoublyLinkedList()
		self.oneItemList = DoublyLinkedList()
		self.twoItemList = DoublyLinkedList()
		self.fiveItemList = DoublyLinkedList()

		self.one = [3]
		self.two = [2, 9]
		self.five = [6, 1, 0, 5, 8]

		for i in self.one:
			self.oneItemList.append(i)

		for i in self.two:
			self.twoItemList.append(i)

		for i in self.five:
			self.fiveItemList.append(i)

	def testEmptyAppend(self):
		self.emptyList.append(4)
		self.assertEqual(self.emptyList.getPosition(0), 4)

	def testOneAppend(self):
		self.oneItemList.append(1)
		self.assertEqual(self.oneItemList.getPosition(0), 3)
		self.assertEqual(self.oneItemList.getPosition(1), 1)

	def testTwoAppend(self):
		self.twoItemList.append(6)
		self.assertEqual(self.twoItemList.getPosition(0), 2)
		self.assertEqual(self.twoItemList.getPosition(1), 9)
		self.assertEqual(self.twoItemList.getPosition(2), 6)

	def testEmptyPrepend(self):
		self.emptyList.prepend(4)
		self.assertEqual(self.emptyList.getPosition(0), 4)

	def testOnePrepend(self):
		self.oneItemList.prepend(1)
		self.assertEqual(self.oneItemList.getPosition(0), 1)

	def testTwoPrepend(self):
		self.twoItemList.prepend(6)
		self.assertEqual(self.twoItemList.getPosition(0), 6)
		self.assertEqual(self.twoItemList.getPosition(1), 2)
		self.assertEqual(self.twoItemList.getPosition(2), 9)

	def testEmptyInsertAfter(self):
		self.assertFalse(self.emptyList.insertAfter(1, 3))

	def testOneInsertAfter(self):
		self.assertTrue(self.oneItemList.insertAfter(2, 0))
		self.assertEqual(self.oneItemList.getPosition(1), 2)
		self.assertFalse(self.oneItemList.find(7))

	def testTwoInsertAfter(self):
		self.assertTrue(self.twoItemList.insertAfter(7, 0))
		self.assertEqual(self.twoItemList.getPosition(1), 7)
		self.assertFalse(self.twoItemList.find(3))

	def testEmptyRemoveBeginning(self):
		self.assertFalse(self.emptyList.removeBeginning())

	def testOneRemoveBeginning(self):
		self.assertTrue(self.oneItemList.removeBeginning())
		self.assertFalse(self.oneItemList.getPosition(0))

	def testTwoRemoveBeginning(self):
		self.assertTrue(self.twoItemList.removeBeginning())
		self.assertEqual(self.twoItemList.getPosition(0), 9)

	def testEmptyRemoveEnd(self):
		self.assertFalse(self.emptyList.removeEnd())

	def testOneRemoveEnd(self):
		self.assertTrue(self.oneItemList.removeEnd())
		self.assertFalse(self.oneItemList.getPosition(0))

	def testTwoRemoveEnd(self):
		self.assertTrue(self.twoItemList.removeEnd())
		self.assertEqual(self.twoItemList.getPosition(0), 2)

	#def testRemoveAfter(self):

	def testEmptyFind(self):
		self.assertFalse(self.emptyList.find(0))

	def testOneFind(self):
		self.assertFalse(self.oneItemList.find(0))
		self.assertTrue(self.oneItemList.find(3))

	def testTwoFind(self):
		self.assertTrue(self.fiveItemList.find(8))
		self.assertFalse(self.fiveItemList.find(3))

	def testFiveFind(self):
		self.assertTrue(self.fiveItemList.find(0))
		self.assertFalse(self.fiveItemList.find(2))
class TestDoublyLinkedList(unittest.TestCase):

    def setUp(self):
        self.my_list = DoublyLinkedList()

    def test_basic_initialization_and_repr(self):
        self.assertEqual(repr(self.my_list), '[]')

    def test_append(self):
        self.my_list.append(4)
        self.my_list.append(3)
        self.my_list.append(7)
        self.my_list.append(-17)
        self.assertEqual(repr(self.my_list), '[4, 3, 7, -17]')

    def test_prepend(self):
        self.my_list.prepend(4)
        self.my_list.prepend(3)
        self.my_list.prepend(7)
        self.my_list.prepend(-17)
        self.assertEqual(repr(self.my_list), '[-17, 7, 3, 4]')

    def test_insert_after(self):
        self.my_list.insert_after(None, 4)
        self.my_list.insert_after(None, 3)
        self.my_list.insert_after(self.my_list.tail, 7)
        self.my_list.insert_after(self.my_list.head, -17)
        self.assertEqual(repr(self.my_list), '[3, -17, 4, 7]')

    def test_insert_sorted(self):
        self.my_list.insert_after(None, 4)
        self.my_list.insert_after(None, 3)
        self.my_list.insert_after(None, 7)
        self.assertEqual(repr(self.my_list), '[7, 3, 4]')
        self.my_list.insert_sorted(2)
        self.my_list.insert_sorted(8)
        self.assertEqual(repr(self.my_list), '[2, 7, 3, 4, 8]')
        self.my_list.remove(self.my_list.head)
        self.my_list.remove(self.my_list.head)
        self.my_list.remove(self.my_list.head)
        self.my_list.remove(self.my_list.head)
        self.my_list.remove(self.my_list.head)
        self.my_list.insert_sorted(8)
        self.my_list.insert_sorted(7)
        self.my_list.insert_sorted(6)
        self.my_list.insert_sorted(5)
        self.assertEqual(repr(self.my_list), '[5, 6, 7, 8]')

    def test_remove(self):
        self.my_list.append(4)
        self.my_list.append(3)
        self.my_list.append(7)
        self.my_list.append(-17)
        self.assertEqual(repr(self.my_list), '[4, 3, 7, -17]')
        self.my_list.remove(self.my_list.head)
        self.assertEqual(repr(self.my_list), '[3, 7, -17]')
        self.my_list.remove(self.my_list.head.next)
        self.assertEqual(repr(self.my_list), '[3, -17]')
        self.my_list.remove(self.my_list.tail)
        self.assertEqual(repr(self.my_list), '[3]')
        self.my_list.remove(self.my_list.head)
        self.my_list.remove(self.my_list.head)
        self.assertEqual(repr(self.my_list), '[]')

    def test_array(self):
        self.my_list.append(4)
        self.my_list.append(3)
        self.my_list.append(7)
        self.my_list.append(-17)
        self.assertEqual(self.my_list.array(), [4, 3, 7, -17])

    def test_reverse_array(self):
        self.my_list.append(4)
        self.my_list.append(3)
        self.my_list.append(7)
        self.my_list.append(-17)
        self.assertEqual(self.my_list.reverse_array(), [-17, 7, 3, 4])

    def test_search(self):
        self.my_list.append(4)
        self.my_list.append(3)
        self.my_list.append(-17)
        self.my_list.append(7)
        self.assertEqual(self.my_list.search(4).data, 4)
        self.assertEqual(self.my_list.search(3).data, 3)
        self.assertEqual(self.my_list.search(-17).data, -17)
        self.assertEqual(self.my_list.search(17), None)

    def test_reverse(self):
        self.my_list.append(4)
        self.my_list.append(3)
        self.my_list.append(7)
        self.my_list.append(-17)
        self.assertEqual(repr(self.my_list), '[4, 3, 7, -17]')
        self.my_list.reverse()
        self.assertEqual(repr(self.my_list), '[-17, 7, 3, 4]')
        self.my_list.reverse()
        self.assertEqual(repr(self.my_list), '[4, 3, 7, -17]')

    def test_remove_duplicates(self):
        self.my_list.append(4)
        self.my_list.append(3)
        self.my_list.append(3)
        self.my_list.append(3)
        self.my_list.append(7)
        self.my_list.append(-17)
        self.assertEqual(repr(self.my_list), '[4, 3, 3, 3, 7, -17]')
        self.my_list.remove_duplicates()
        self.assertEqual(repr(self.my_list), '[4, 3, 7, -17]')
class Deque:
    def __init__(self, iterable=None):
        # Initialize a new Doubly linked list to store the items
        self.list = DoublyLinkedList()
        if iterable is not None:
            for item in iterable:
                self.append(item)

    def __repr__(self):
        """Return a string representation of this stack."""
        return 'Stack({} items, top={}, last={}'.format(
            self.length(), self.peek_first(), self.peek_last())

    def is_empty(self):
        """Return True if this stack is empty, or False otherwise."""
        return self.list.is_empty()

    def length(self):
        """Return the number of items in this stack."""
        return self.list.size

    def append(self, item):
        """ Insert the given item to the end of the double ended queue"""
        self.list.append(item)

    def prepend(self, item):
        """ Insert the given item to the end of the double ended queue"""
        self.list.prepend(item)

    def peek_first(self):
        """Return the item on the top of this queue without removing it,
        or None if this queue is empty."""
        if self.is_empty():
            return None
        else:
            return self.list.head.data

    def peek_last(self):
        """Return the item on the end of this queue without removing it,
        or None if this queue is empty."""
        if self.is_empty():
            return None
        else:
            return self.list.tail.data

    def pop_first(self):
        """Remove and return the item on the top of this queue,
        or raise ValueError if this queue is empty.
        Running time: O(1) – Since the targeted node is the head of the linked list"""
        if self.is_empty():
            raise ValueError('Stack is empty')
        else:
            top_value = self.list.head.data
            self.list.delete(top_value)
            return top_value

    def pop_last(self):
        """Remove and return the item on the end of this queue,
        or raise ValueError if this queue is empty.
        Running time: O(1) – Since the targeted node is the tail of the linked list"""
        if self.is_empty():
            raise ValueError('Stack is empty')
        else:
            top_value = self.list.tail.data
            self.list.delete(top_value)
            return top_value
 def test_iter(self):
     llist = DoublyLinkedList()
     llist.append('A')
     llist.append('B')
     self.assertEqual(repr(llist), 'A, B')
Example #32
0
 def test_append_start_filled(self):
     linkedlist = DoublyLinkedList([1, 2, 3])
     for i in range(10):
         linkedlist.append(i)
    llist = DoublyLinkedList()

    llist.head = Node(1)
    second = Node(2)
    third = Node(4)

    llist.head.next = second
    second.next = third

    llist.print_list()

    llist.insert_after(2, 3)
    print('\nInserting 3 after 2 ..')
    llist.print_list()

    llist.append(5)
    print('\nAppending 5 ..')
    llist.print_list()

    llist.insert_before(2, 0)
    print('\nInserting 0 before 2 ..')
    llist.print_list()

    llist.delete_node_position(4)
    print('\nDeleting node at position 4 ..')
    llist.print_list()

    print('\nCount:', llist.get_count())

    llist.delete_node(4)
    print('\nDeleting 4 ..')
 def test_add_after_last_node(self):
     llist = DoublyLinkedList()
     llist.append('A')
     llist.append('B')
     llist.add_after_node('B', 'C')
     self.assertEqual(repr(llist), 'A, B, C')
from doubly_linked_list import DoublyLinkedList

my_list = DoublyLinkedList()
my_list.print()

for i in range(10):
    my_list.append(i + 1)

my_list.print()

for i in range(10):
    my_list.prepend(i + 1)

my_list.print()

value = my_list.access(3)
print('my_list.access(3) = ' + str(value))

my_list.insert(8, 128)
my_list.print()

my_list.remove(4)
my_list.print()

my_list.set_head(10)
my_list.print()
my_list.print_inverse()
Example #36
0
 def test_append_start_empty(self):
     linkedlist = DoublyLinkedList()
     for i in range(10):
         linkedlist.append(i)