class Stack(object): # initializes stack def __init__(self): self.__linked_list = SinglyLinkedList() self.length = 0 # returns string representation of stack as "[item1, item2, ...]" def __repr__(self): return repr(self.__linked_list) # returns boolean value of whether or not stack is empty def is_empty(self): return self.length == 0 # returns length of stack def get_length(self): return self.length # pushes new item to top of stack def push(self, item): self.__linked_list.prepend(item) self.length += 1 # returns item at top of stack and removes it def pop(self): item = self.__linked_list.head.data self.__linked_list.remove_after(None) self.length -= 1 return item # returns item at the top of stack without removing def peek(self): return self.__linked_list.head.data
class Queue: """Queue data structure implementation using linked list""" def __init__(self, max_size): if not isinstance(max_size, int): raise Exception('size must be int greater than 0') if (max_size < 1): raise Exception('size must be int greater than 0') self.top = 0 self.max_size = max_size self.llist = SinglyLinkedList() def enqueue(self, val): """add item into queue""" if self.top >= self.max_size: raise Exception('Queue is full') self.llist.add(val) self.top += 1 def dequeue(self): """remove item from queue""" if self.top == 0: raise Exception('Queue is empty') self.top -= 1 return self.llist.remove_tail()
def test_display_method_returns_string_of_none_if_list_is_empty(): """Test that the display method of the Singly Linked List class returns the string of None of the list is empty.""" ll = SinglyLinkedList() assert ll.display() == 'None'
class StackLinkedList: """ This is a Linked List based implementation of a stack """ # Creates an empty list with Linked List def __init__(self): self._items = SinglyLinkedList() # Returns True if stack is Empty otherwise returns False def isEmpty(self): return self._items.node_counter == 0 def __len__(self): return self._items.node_counter # Returns the top item of the stack without removing it def peek(self): assert not self.isEmpty(), "Cannot peek at an empty stack" return self._items.get_head() # Remove and return the last item of the stack def pop(self): assert not self.isEmpty(), "Cannot pop from an empty stack" last_item = self.peek() self._items.delete_start() return last_item # Push an item at the top of the stack def push(self, item): self._items.insert_start(item)
def is_palindrome(l: SinglyLinkedList) -> bool: """ 判断是否是回文字符串 :param l: :return: """ l.print_all() fast = slow = l._head while fast and fast.next: slow = slow.next fast = fast.next.next reverse_node = reverse(slow) head_node = l._head is_palin = True while head_node and reverse_node: if head_node.data == reverse_node.data: head_node = head_node.next reverse_node = reverse_node.next else: is_palin = False break return is_palin
class Stack: """Stack data structure implementation using linked list""" def __init__(self, max_size): if not isinstance(max_size, int): raise Exception('size must be int greater than 0') if (max_size < 1): raise Exception('size must be int greater than 0') self.top = 0 self.max_size = max_size self.llist = SinglyLinkedList() def push(self, val): """Push item onto stack""" if self.top >= self.max_size: raise Exception('Stack is full') self.llist.add(val) self.top += 1 def pop(self): """Pop item from stack""" if self.top == 0: raise Exception('Stack is empty') self.top -= 1 return self.llist.remove()
class Queue: def __init__(self): self.size = 0 self.storage = SinglyLinkedList() def __len__(self): # returns the length of the queue return self.size def enqueue(self, value): # increase the size of the queue by one self.size += 1 # add the new value to the tail of our list self.storage.add_to_tail(value) def dequeue(self): # return 0 if nothing is in the queue if self.size == 0: return None # decrement the size of the queue by one self.size -= 1 # remove the value from the head of our list and return the value of the # removed head value = self.storage.remove_head() return value
def test_add_node_method_adds_new_Node_class_to_Singly_Linked_Class(): """Test that the add_node method of the Singly Linked List class successfully adds a new instance of the Node class.""" ll = SinglyLinkedList() ll.add_node(1) assert isinstance(ll.head, Node)
def merge(left, right): """ Merges two linked lists, sorting by data in nodes Returns a new, merged list Runs in O(n) time """ # Create a new linked list that contains nodes from # merging left and right merged = SinglyLinkedList() # Add a fake head that is discarded later merged.add(0) # Set current to the head of the linked list current = merged.head # Obtain head nodes for left and right linked lists left_head = left.head right_head = right.head # Iterate over left and right until we reach the tail node # of either while left_head or right_head: # If the head node of left is None, we're past the tail # Add the node from right to merged linked list if left_head is None: current.next_node = right_head # Call next on right to set loop condition to False right_head = right_head.next_node # If the head node of right is None, we're past the tail # Add the tail node from left to merged linked list elif right_head is None: current.next_node = left_head # Call next on left to set loop condition to False left_head = left_head.next_node else: # Not at either tail node # Obtain node data to perform comparison operations left_data = left_head.data right_data = right_head.data # If data on left is less than right, set current to left node if left_data < right_data: current.next_node = left_head # Move left head to next node left_head = left_head.next_node # If data on left is greater than right, set current to right node else: current.next_node = right_head # Move right head to next node right_head = right_head.next_node # Move current to next node current = current.next_node # Discard fake head and set first merged node as head head = merged.head.next_node merged.head = head return merged
def test_search_method_returns_node_if_node_containing_data_exists_in_list(): """Test that the search method of the Singly Linked List class returns Node containing given data if it exists in the list.""" ll = SinglyLinkedList() ll.add_node(1) assert ll.search(1) is ll.head
def tearDown(self): print('Finished tests.\n\n') # reset values self.list_1 = SinglyLinkedList(1) self.list_2 = SinglyLinkedList(2) self.list_3 = SinglyLinkedList('apple') self.list_4 = SinglyLinkedList({'name': 'Bob'}) self.list_5 = SinglyLinkedList(None)
def test_pop_method_raises_exception_if_list_is_empty(): """Test that the pop method of the Singly Linked List class raises an exception if the list is empty.""" ll = SinglyLinkedList() with pytest.raises(IndexError): assert ll.pop()
def test_pop_method_returns_data_value_of_head_node(): """Test that the pop method of the Singly Linked List class returns the data value of the head Node.""" ll = SinglyLinkedList() ll.add_node(10) assert ll.pop() == 10
def test_search_method_raises_exception_if_list_is_empty(): """Test that the search method of the Singly Linked List class raises a LookupError if the list is empty.""" ll = SinglyLinkedList() with pytest.raises(LookupError): assert ll.search(1)
def test_delete_node_method_raises_exception_if_list_is_empty(): """Test that the delete_node method of the Singly Linked List class raises an exception if used on an empty list.""" ll = SinglyLinkedList() with pytest.raises(LookupError): assert ll.delete_node(1)
def test_delete_node_method_returns_data_value_of_deleted_node(): """Test that the delete_node method of the Singly Linked List class returns the data value of the Node that it deletes.""" ll = SinglyLinkedList() ll.add_node(1) assert ll.delete_node(1) == 1
def setUp(self): print('Starting Singly Linked List Tests..\n\n') # set values self.list_1 = SinglyLinkedList(1) self.list_2 = SinglyLinkedList(2) self.list_3 = SinglyLinkedList('apple') self.list_4 = SinglyLinkedList({'name': 'Bob'}) self.list_5 = SinglyLinkedList(None)
def test_delete_node_raises_exception_if_node_with_given_data_not_in_list(): """Test that the delete_node method of the Singly Linked List class raises an exception if no Node with the given data exists in the list.""" ll = SinglyLinkedList() ll.add_node(1) with pytest.raises(LookupError): assert ll.delete_node(5)
def test_search_method_raises_exception_if_node_containing_data_absent(): """Test that the search method of the Singly Linked List class raises a LookupError if no Node in list contains given data.""" ll = SinglyLinkedList() ll.add_node(1) with pytest.raises(LookupError): assert ll.search(5)
def test_add_node_method_replaces_None_value_in_head_with_Node_object(): """Test that the add_node method of the Singly Linked List class replaces the value of None in an empty list's head attribute with the Node class object.""" ll = SinglyLinkedList() ll.add_node(1) assert ll.head is not None assert hasattr(ll.head, 'data') and hasattr(ll.head, 'next_node')
def test_add_node_method_replaces_head_when_multiple_nodes_added(): """Test that the add_node method of the Singly Linked List class consistently replaces the head of the list with the newest added Node.""" ll = SinglyLinkedList() for i in range(5): ll.add_node(i) assert ll.head.data == i
def main2(): sll = SinglyLinkedList() for i in range(1,10): sll.append(i) print(sll) print(len(sll)) sll[-9] = 100 print(sll[-9]) print(sll[1:3])
def test_display_method_returns_correct_visual_representation_of_list(): """Test that the display method of the Singly Linked List returns an accurate visual representation of the list, complete with all Nodes.""" ll = SinglyLinkedList() for i in range(3): ll.add_node(i) assert ll.display() == '[ 2 ] -> [ 1 ] -> [ 0 ] -> None'
def __init__(self, max_size): if not isinstance(max_size, int): raise Exception('size must be int greater than 0') if (max_size < 1): raise Exception('size must be int greater than 0') self.top = 0 self.max_size = max_size self.llist = SinglyLinkedList()
def test_creation(self): """ Test the creation of a list and the fundamental object attributes. """ sll = SinglyLinkedList() # The list starts off with no 'first' Node - this is an empty list. self.assertIs(sll.first_node, None) # We can create a list with 'first_node' populated. sll = SinglyLinkedList(Node('hello')) self.assertEquals(sll.first_node.data, 'hello')
def test_inti(self): llist = SinglyLinkedList() self.assertEqual(llist.size, 0) self.assertEqual(llist.head, None) llist = SinglyLinkedList(5) self.assertEqual(llist.size, 1) self.assertEqual(llist.head.data, 5) llist = SinglyLinkedList([1, 2, 3]) self.assertEqual(llist.size, 3) self.assertEqual(llist.head.data, 1) self.assertEqual(llist.head.next.data, 2) self.assertEqual(llist.head.next.next.data, 3)
def test_move_to_front(self): """ Tests that a Node has been moved to the front of the list. """ sll = SinglyLinkedList() sll.add_to_head(1) sll.add_to_head("testing") node = sll.head sll.add_to_head(5) sll.move_to_front(node) self.assertEqual(sll.head.value, "testing") self.assertEqual(len(sll), 3)
def test_peek_last(self): llist = SinglyLinkedList() self.assertRaises(Exception, llist.peek_last) llist.insert_first(0) self.assertEqual(llist.peek_last(), 0) llist.insert_first(-1) self.assertEqual(llist.peek_last(), 0)
class Stack: def __init__(self): self.s = LinkedList() self.head = self.s.sentinel def push(self, x): newnode = Node(x) self.s.insert(newnode) def pop(self): x = self.s.head if x is None: raise UnderFlowError self.s.delete(self.s.head) return x
def test_append(self): """ Test an append method. """ sll = SinglyLinkedList() sll.append(Node('first')) sll.append(Node('second')) sll.append(Node('third')) self.assertEquals(str(sll), 'first, second, third')
def test_inserts(self): """ Test list inserts. """ sll = SinglyLinkedList(Node('first')) sll.insert_after(sll.first_node, Node('second')) self.assertEquals(sll.first_node.data, 'first') self.assertEquals(sll.first_node.next_node.data, 'second') sll.insert_beginning(Node('before the first')) self.assertEquals(sll.first_node.data, 'before the first') self.assertEquals(sll.first_node.next_node.data, 'first') self.assertEquals(sll.first_node.next_node.next_node.data, 'second') self.assertEquals(str(sll), 'before the first, first, second')
def test_exists(self): """ Tests for membership. """ sll = SinglyLinkedList() node1, node2, node3 = Node(1), Node(2), Node(3) sll.append(node1) sll.append(node2) sll.append(node3) self.assertTrue(sll.exists(node1)) self.assertTrue(sll.exists(node2)) self.assertTrue(sll.exists(node3)) self.assertFalse(sll.exists(Node(4))) # Membership is based on object identity, not value self.assertFalse(sll.exists(Node(1)))
def testReverse(self): slist = SinglyLinkedList() slist.insert_after(None, 14) slist.insert_after(None, 13) slist.insert_after(None, 12) slist.insert_after(None, 11) slist.reverse() actual = to_array(slist) expected = [14, 13, 12, 11] self.assertEqual(expected, actual)
def test_delete(self): """ Test a delete method. """ sll = SinglyLinkedList() node1, node2, node3 = Node(1), Node(2), Node(3) sll.append(node1) sll.append(node2) sll.append(node3) self.assertEquals(str(sll), '1, 2, 3') sll.delete(node2) self.assertEquals(str(sll), '1, 3') # It silently handles missing items sll.delete(Node(4)) self.assertEquals(str(sll), '1, 3')
def test_removals(self): """ Test list removals. """ node1 = Node('first') sll = SinglyLinkedList(node1) node2 = Node('second') sll.insert_after(node1, node2) self.assertEquals(str(sll), 'first, second') sll.remove_after(node1) self.assertEquals(str(sll), 'first') sll.insert_after(node1, node2) sll.remove_beginning() self.assertEquals(str(sll), 'second')
def testInsertion(self): slist = SinglyLinkedList() tail = slist.insert_after(None, 10) slist.insert_after(None, 11) actual = to_array(slist) expected = [11, 10] self.assertEqual(expected, actual) slist.insert_after(tail, 12) actual = to_array(slist) expected = [11, 10, 12] self.assertEqual(expected, actual)
def testDeletion(self): slist = SinglyLinkedList() tail = slist.insert_after(None, 13) slist.insert_after(None, 12) actual = to_array(slist) expected = [12, 13] self.assertEqual(expected, actual) slist.delete_after(tail) actual = to_array(slist) expected = [12, 13] self.assertEqual(expected, actual) slist.delete_after(slist.head) actual = to_array(slist) expected = [12] self.assertEqual(expected, actual)
def setUp(self): self.my_list = SinglyLinkedList()
class TestSinglyLinkedList(unittest.TestCase): def setUp(self): self.my_list = SinglyLinkedList() 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_after(None) self.my_list.remove_after(None) self.my_list.remove_after(None) self.my_list.remove_after(None) self.my_list.remove_after(None) 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]') self.my_list.reverse() self.assertEqual(repr(self.my_list), '[8, 7, 6, 5]') def test_remove_after(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_after(None) self.assertEqual(repr(self.my_list), '[3, 7, -17]') self.my_list.remove_after(self.my_list.head) self.assertEqual(repr(self.my_list), '[3, -17]') self.my_list.remove_after(self.my_list.tail) self.assertEqual(repr(self.my_list), '[3, -17]') self.my_list.remove_after(None) self.my_list.remove_after(None) self.my_list.remove_after(None) 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_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]')
def __init__(self): self.__linked_list = SinglyLinkedList() self.length = 0
while fast and fast._next: slow = slow._next fast = fast._next._next position += 1 reverse_node = reverse(slow) head_node = l._head is_palin = True while (head_node and reverse_node): if (head_node.data == reverse_node.data): head_node = head_node._next reverse_node = reverse_node._next else: is_palin = False break return is_palin if __name__ == '__main__': # the result should be False, True, True, True, True test_str_arr = ['ab', 'aa', 'aba', 'abba', 'abcba'] for str in test_str_arr: l = SinglyLinkedList() for i in str: l.insert_value_to_head(i) print(is_palindrome(l))
from singly_linked_list import SinglyLinkedList x = SinglyLinkedList() x.insertAtBegin(5) x.insertAtBegin(10) x.insertAtBegin(15) x.insertAtBegin(None) print(x.search(None)) print(x.__str__())
def test_print(self): """ Test the list printing. """ sll = SinglyLinkedList(Node('first')) sll.insert_after(sll.first_node, Node('second')) self.assertEquals(str(sll), 'first, second')