def test_insert(): print("------TEST INSERT------") s_list = LinkedList() n1 = Node(12) n2 = Node(55) n3 = Node(128) n4 = Node(55) n5 = Node(130) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 s_list.add_in_tail(n1) s_list.add_in_tail(n2) s_list.add_in_tail(n3) s_list.add_in_tail(n4) s_list.add_in_tail(n5) s_list.print_all_nodes() print("---------------") try: nnew = Node(1001) s_list.insert(n2, nnew) s_list.print_all_nodes() print("head", s_list.head, s_list.head.value) print("tail", s_list.tail, s_list.tail.value) node = s_list.head count = 0 while node != None: if node.value == 55 and node.next.value == 1001: count = count + 1 if node.value == 1001 and node.next.value == 128: count = count + 1 node = node.next if count == 2: print("test insert success") else: print("test insert failed") except Exception: print("error test insert") print("------empty linked list------") s_list_empty = LinkedList() s_list_empty.print_all_nodes() nnew_empty = Node(10001) try: s_list_empty.insert(n2, nnew_empty) s_list_empty.print_all_nodes() print(s_list_empty.head, s_list_empty.head.value) print(s_list_empty.tail, s_list_empty.tail.value) if s_list_empty.head.value == 10001 and s_list_empty.tail.value == 10001 \ and s_list_empty.head == s_list_empty.tail: print("test insert in empty list success") else: print("test insert in empty list failed") except Exception: print("error test insert")
def test_linking_nodes(self): node1 = Node('A') node2 = Node('B') node3 = Node('C') # Link nodes together node1.next = node2 node2.next = node3 # Node links should be transitive assert node1.next is node2 # One link assert node1.next.next is node3 # Two links
def test_sum_lists(self): head1 = Node(5) head1.next = Node(8) head1.next.next = Node(7) head2 = Node(3) head2.next = Node(8) result_sum = sum_lists(head1, head2) self.assertEqual(result_sum.value, 8) self.assertEqual(result_sum.next.value, 6) self.assertEqual(result_sum.next.next.value, 8) head3 = None head4 = None result_sum2 = sum_lists(head3, head4) self.assertEqual(result_sum2, None)
def test_linking_nodes(self): node1 = Node('A') node2 = Node('B') node3 = Node('C') # Link nodes together node1.next = node2 node1.prev = None node2.next = node3 node2.prev = node1 node3.prev = node2 node3.next = None # Node links should be transitive assert node1.prev is None assert node1.next is node2 # One link assert node2.prev is node1 assert node1.next.next is node3 # Two links assert node3.prev is node2 assert node3.next is None
def insert(self, value): node = Node(value) node.next = None if self.length == 0: self.head = self.last = node else: last = self.last last.next = node self.last = node self.length += 1
def push(self, item): """Insert the given item on the top of this stack. Running time: O(1) because we only have to reassign the head pointer which does not depend on the number of items in the list """ new_node = Node(item) self.list.size += 1 # increment size if self.list.head is None: # case where list is empty self.list.head = new_node return new_node.next = self.list.head self.list.head = new_node
def FlattenNode(pre: Node, cur: Node) -> Node: if not cur: return pre pre.next = cur cur.prev = pre tmpnode = cur.next childnode = FlattenNode(cur, cur.child) cur.child = None return FlattenNode(childnode, tmpnode)
def push(self, item): """Insert the given item on the top of this stack. Running time: O(???) – Why? [TODO]""" # TODO: Push given item if self.list.is_empty(): new_node = Node(item) self.list.head = new_node else: node = self.list.head new_node = Node(item) new_node.next = node self.list.head = new_node
def test_delete_middle_node(self): head = Node(2) head.next = Node(1) head.next.next = Node(3) head.next.next.next = Node(6) head2 = None delete_middle_node(head.next.next) self.assertEqual(head.value, 2) self.assertEqual(head.next.value, 1) self.assertEqual(head.next.next.value, 6) delete_middle_node(head2) self.assertEqual(head2, None)
def check_palindrome(head): if head is None: return False reversed_linked_list = Node(head.data) reversed_linked_list.next = None current_node = head.next #reverse the list while current_node is not None: new_node = Node(current_node.data) new_node.next = reversed_linked_list reversed_linked_list = new_node current_node = current_node.next current_node = head while current_node is not None and reversed_linked_list is not None: if current_node.data != reversed_linked_list.data: return False current_node = current_node.next reversed_linked_list = reversed_linked_list.next return True
def sum_lists(num1, num2): if num1 is None or num2 is None: return num1 or num2 carry = 0 # We use a dummy node as the head of the sum list. # We can also set the head as None. # But this needs more if-else checks as we move head through the list using head.next as None has no next parameter. head = new_head = Node(0) while num1 is not None or num2 is not None: # caution: don't forget to check for None if num1 is None: num1_value = 0 else: num1_value = num1.value if num2 is None: num2_value = 0 else: num2_value = num2.value num_sum = carry + num1_value + num2_value if num_sum >= 10: carry = 1 num_sum = num_sum % 10 else: carry = 0 current = Node(num_sum) head.next = current head = head.next # caution: don't forget to check for None if num1 is not None: num1 = num1.next if num2 is not None: num2 = num2.next if carry > 0: current.next = Node(carry) return new_head.next
def set_up(l1, l2): intersecting_node = Node(5) intersecting_node.next = Node(6) intersecting_node.next.next = Node(7) l1tail = l1.head l2tail = l2.head while l1tail.next is not None: l1tail = l1tail.next l1tail.next = intersecting_node while l2tail.next is not None: l2tail = l2tail.next l2tail.next = intersecting_node
def test_partition(self): head = Node(5) head.next = Node(3) head.next.next = Node(1) head.next.next.next = Node(2) head.next.next.next.next = Node(4) head2 = None result_head = partition(head, 3) self.assertEqual(result_head.value, 1) self.assertEqual(result_head.next.value, 2) self.assertEqual(result_head.next.next.value, 5) self.assertEqual(result_head.next.next.next.value, 3) self.assertEqual(result_head.next.next.next.next.value, 4) result_head2 = partition(head2, 3) self.assertEqual(result_head2, None)
def case1(self, file): try: fh = open(file, "r") fh.readline() #new node preNode = Node(None) self.linkedList.setStart(None) for line in fh: arr = list(line.split(",")) # New product product = Product(arr[0], arr[1], float(arr[2]), int(arr[3])) node = Node(product) #add start if (self.linkedList.getStart() is None): self.linkedList.setStart(node) # connect node preNode.next = node preNode = node fh.close() print("The file is loaded successfully!") except: print("File-path is not correct!")
def test_node_attributes(): head = Node(1) assert head.prev is None assert head.next is None previous = Node(0) head.prev = previous assert head.prev is previous assert head.next is None assert head.data == 1 assert head.prev.prev is None assert head.prev.data == 0 assert repr(previous) == "Node(0)" next = Node(2) head.next = next assert head.prev is previous assert head.next is next assert head.data == 1 assert head.next.next == None assert head.prev.prev == None assert head.next.data == 2 assert repr(next) == "Node(2)"
def removeElements(head, data): """ :type head: ListNode :type data: int :rtype: ListNode """ # Creates a dummy node starter head # Ensures the case of deleting the head node in LL dummy_head = Node(-1) dummy_head.next = head current_node = dummy_head # Traverse through the LL while current_node.next is not None: # Once the data is found, change the pointer to the next value if current_node.next.data == data: current_node.next = current_node.next.next else: current_node = current_node.next # Base case traversal return dummy_head.next # Head of the node
def prepend(self, item, number_of_columns): """Insert the given item at the head of this linked list. TODO: Running time: O(1) Why and under what conditions?""" # TODO: Create new node to hold given item node = Node(item) if type(item) is list: node.data = LinkedList(node.data) # TODO: Prepend node before head, if it exists if self.is_empty(): self.head = node self.tail = node else: node.next = self.head self.head = node else: columns = 0 for node in self: if columns == number_of_columns: linkedlist = node.data linkedlist.prepend(item) break else: # count columns columns += 1
while (head_1): if head_1 == head_2: return head_1 head_1 = head_1.next head_2 = head_2.next # TESTS a = Node('a') b = Node('b') c = Node('c') d = Node('d') a.next = b b.next = c c.next = d e = Node('e') f = Node('f') h = Node('g') g = Node('h') e.next = f f.next = h # h.next = c list_1 = LinkedList() list_2 = LinkedList()
# set the current to the next node current = current.next # Get the middle node after your iteration middle_node = int(count / 2) # Redefine the current for it to be ready to iterate again current = head # Iterate through the LL once more by the range of the middle variable for _ in range(middle_node): # Set the current to the next node current = current.next # return the current because it should be the middle now return current # Test Code # 1 -> 2 -> 3 -> 4 -> 5 -> // node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 print(find_middle_node_one_pass(node1))
# return pointer_1 to the head if it goes faster than pointer_2 pointer_1 = list_1.head while pointer_2 != pointer_1: pointer_1 = pointer_1.next pointer_2 = pointer_2.next return pointer_1 # TESTS a = Node('a') b = Node('b') c = Node('c') a.next = b b.next = c c.next = a list_1 = LinkedList() list_1.appendNode(a) list_1.appendNode(b) list_1.appendNode(c) res = loopDetection(list_1) if res: print(res.val) else: print(res)
from linkedlist import Node, print_list_from_node def remove_middle(node): node.value = node.next.value node.next = node.next.next node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 print_list_from_node(node1) remove_middle(node3) print_list_from_node(node1)
# Let k be the size of the cycle. Let the hare be exactly k steps # in front of the tortoise, and move both one step at a time. When # the tortoise gets to the first node in the cycle the hare will # also be there because N + k = N for every N in the # cycle. Since they cannot meet before the cycle, the first place # they meet is the beginning of the cycle tortoise = node hare = node for i in range(size): hare = hare.next while True: if hare == tortoise: return hare hare = hare.next tortoise = tortoise.next n1 = Node(1) n2 = Node(2) n3 = Node(3) n4 = Node(4) n5 = Node(5) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n3 print find_first_in_loop(n3)
def push(self, data): node = Node(data) node.next = self.head self.head = node self.length += 1
# program for deleting the node given only it's reference, not any head ref # importing all linkedlist main functions from linkedlist import LList, Node # functions for deleting given node # logic is to simply swap the given node pointer data with next node data, and then delete the next node which contains now that original data by pointing and adjusting pointer by skipping the deleted node. def delete_val(node): if not node: return # swapping the current node and next node node.next.data, node.data = node.data, node.next.data # deleting the node by skipping the connection between current node and swapped node node.next = node.next.next # main function if __name__ == '__main__': l = LList() head = Node(4) first_node = Node(5) second_node = Node(1) third_node = Node(9) head.next, first_node.next, second_node.next, third_node.next = first_node, second_node, third_node, None # 4->5->1->9 delete_val(first_node) # deletes 5 ptr = head while(ptr): print(ptr.data, end = " ") ptr = ptr.next # prints 4->1->9
# https://media.geeksforgeeks.org/wp-content/cdn-uploads/gq/2013/03/Linkedlist.png from linkedlist import Node from linkedlist import LinkedList letterlist = LinkedList() letterlist2 = LinkedList() head = Node("A") node2 = Node("B") node3 = Node("C") node4 = Node("D") head.next = node2 node2.next = node3 node3.next = node4 node4.next = None letterlist.head = head # letterlist.printList() # letterlist.pushFront("X") # letterlist.printList() # letterlist.pushBack("Z") # letterlist.printList() letterlist2.pushBack("Y") letterlist2.printList()
from linkedlist import Node from linkedlist import LinkedList def solution(linkedlist): dic = {} cur = linkedlist.head.next while cur: if cur in dic: print(cur.data) return cur else: dic[cur] = True cur = cur.next return False ll = LinkedList(['A', 'B']) c_node = Node('C') ll.appendNode(c_node) node = Node('D') ll.appendNode(node) node = Node('E') node.next = c_node ll.appendNode(node) solution(ll)
def insertFirst(theList,data): node = Node(data) node.next = theList.first theList.first = node
result1.printLinkedList() print("============= TEST 2 ===============") num3 = Node(7) num3.createLinkedListFromList([1,6]) num4 = Node(5) num4.createLinkedListFromList([9,2]) result2 = add_linked_list(num3, num4) result2.printLinkedList() print("============= TEST 3 ===============") num5 = Node(5) num5.createLinkedListFromList([6,7]) num6 = Node(4) result3 = add_linked_list(num5, num6) result3.printLinkedList() print("============= TEST 4 ===============") num7 = Node(0) num7.createLinkedListFromList([0,1]) num8 = Node(0) num8.next = Node(5) result4 = add_linked_list(num7, num8) result4.printLinkedList() print("============= TEST 5 ===============") num9 = Node(0) num10 = Node(9) result5 = add_linked_list(num9, num10) result5.printLinkedList()