if p1.key == key and p2: # standard deletion case (p2 exists) p2.next = p1.next p1 = p1.next # don't update p2 since it's still prev elif p1.key == key and not p2: # special case; head itself = val (because p2 is None) ret_val = p1.next # update resulting head node to exclude this node p1 = p1.next # don't update p2 else: # just advance as normal p2 = p1 p1 = p1.next return ret_val if __name__ == '__main__': t = SinglyLinkedList() t.insert(6) tmp = SinglyLinkedList() tmp.head = remove_occurrences(t.head, 6) tmp.print_list() t = SinglyLinkedList() t.insert(6) t.insert(6) t.insert(6) t.insert(6) tmp = SinglyLinkedList() tmp.head = remove_occurrences(t.head, 6) tmp.print_list() t = SinglyLinkedList()
s1 += str(l1.key) l1 = l1.next while l2: # Same for list 2 s2 += str(l2.key) l2 = l2.next s3 = str(int(s1) + int(s2)) # s3 contains the casted sum string l3_h = l3 = ListNode(-1) # dummy for c in s3: l3.next = ListNode(int(c)) l3 = l3.next return l3_h.next if __name__ == '__main__': # T1 l1 = SinglyLinkedList() l2 = SinglyLinkedList() l1.insert(2) l1.insert(4) l1.insert(3) l2.insert(5) l2.insert(6) l2.insert(4) l1.print_list() print("+") l2.print_list() print("=") head = sum_lists(l1.head, l2.head) ans = SinglyLinkedList() ans.head = head ans.print_list()
Algorithm: Simple: intersecting nodes have the same last node :param l1: list 1 :param l2: ist 2 :Time: O(n+m) :return: whether they intersect """ while l1.next: # get last node of l1 l1 = l1.next while l2.next: # get last node of l2 l2 = l2.next return l1 == l2 if __name__ == '__main__': # T1 l1 = SinglyLinkedList() l2 = SinglyLinkedList() l1.insert(4) l1.insert(5) l1.insert(2) l1.insert(17) intersect = ListNode(8) # intersecting node l1.current.next = intersect l1.current = intersect l1.insert(9) l1.insert(101) l1.insert(22) l2.insert(4) l2.insert(3) l2.current.next = intersect l2.current = intersect
:return: random node's value """ r, i = 0, 0 # r = result; i = current loop count while h: take = (randint(0, i)) == 0 # take/update r based on probability of 1/i if take: r = h.key # if we take this node, update r i += 1 h = h.next return r if __name__ == '__main__': # Testing 1 n_epochs, n_iter, y_plot, x_plot = 3, int(1e5), [0, 0, 0, 0], [0, 1, 2, 3] test = SinglyLinkedList() test.insert(0) test.insert(1) test.insert(2) test.insert(3) for epoch in range(1, n_epochs + 1): for i in range(n_iter): y_plot[reservoir_sampling(test.head)] += 1 plt.bar(x_plot, y_plot, alpha=0.5) plt.xticks(np.arange(4), ('1', '2', '3', '4')) plt.ylabel('Frequency') plt.show() plt.title('Run ' + str(epoch) + ' with n = ' + str(n_iter)) y_plot = [0, 0, 0, 0]
:return: True if a cycle exists """ p1 = head # p1 be at a distance = d from the head (by advancing by one) p2 = head # p2 be at a distance = 2*d from the head (by advancing by two) while p1 and p2 and p2.next: # If p2 is at last node (and its next is None) then no cycle detected if p1 == p2: # Cycle detected if they meet return True p1 = p1.next p2 = p2.next.next return False # No cycle detected if __name__ == "__main__": test_1 = SinglyLinkedList() for i in range(1, 4 + 1): test_1.insert(i, i ** 2) test_1.current.next = test_1.get(2) # 1->2->3->4->2 print(contains_cycle(test_1.head)) test_2 = SinglyLinkedList() for i in range(1, 4 + 1): test_2.insert(i, i ** 2) test_2.current.next = test_2.get(1) # 1->2->3->4->1 print(contains_cycle(test_2.head)) test_3 = SinglyLinkedList() for i in range(1, 4 + 1): test_3.insert(i, i ** 2) test_3.current.next = test_3.get(3) # 1->2->3->4->3
if l1.key < l2.key: curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next # If a longer list exists, append it to curr.next curr.next = l1 or l2 return dummy.next # Disregard dummy node if __name__ == "__main__": l1 = SinglyLinkedList() l1.insert(5) l1.insert(8) l1.insert(9) l2 = SinglyLinkedList() l2.insert(4) l2.insert(7) l2.insert(8) l2.insert(10) ans = solution(l1.head, l2.head) ans_print = SinglyLinkedList() ans_print.head = ans ans_print.print_list() l1 = SinglyLinkedList()
# note: added more, unnecessary, lines to make it more readable and clear what is happening new_head = recursive(head.next) # recursively reverse the rest last = head.next # notice: last node in the reversed list will be head.next last.next = head # attach last node's link in the reversed list to head last = head # now, the new last is the head last.next = None # to prevent a cycle, set head's next to None head = new_head return head reverse_list = iterative # public function if __name__ == '__main__': print("\n>>>Testing iterative<<<\n") print('Original:') # Test 1 test = SinglyLinkedList() test.insert(1) test.insert(1) test.insert(2) test.insert(3) test.insert(2) test.insert(5) test.insert(4) test.insert(3) test.print_list() new_list_head = iterative(test.head) new_list = SinglyLinkedList() new_list.head = new_list_head print("Reversed:") new_list.print_list() # Test 2
def __init__(self, V: int): self.V = V # total vertices self.E = 0 # total edges self.adjacency_list: List[SinglyLinkedList] = [ SinglyLinkedList() for i in range(V) ] # adjacency list
""" S = Stack() curr = head while curr is not None: S.push(curr) # add each node onto a stack curr = curr.next new_list = ListNode(S.pop().key) new_list_head = new_list while not S.is_empty(): new_list.next = ListNode(S.pop().key) new_list = new_list.next return new_list_head if __name__ == '__main__': test = SinglyLinkedList() test.insert(6) test.insert(5) test.insert(5) test.insert(6) assert is_palindrome(test.head), "Error!" assert alternate(test.head), "Error!" test = SinglyLinkedList() test.insert(1) test.insert(7) test.insert(3) test.insert(8) test.insert(3) test.insert(7) test.insert(1)
:param head: head of list :Time: O(N) :Space: O(1) :return: head of resulting list """ # Two-pointer one-away approach # p1 is one ahead of p2; if p1 = p2, remove p1 by p2.next = p1.next p1, p2 = head, None while p1: if p2 and p1.key == p2.key: p2.next = p1.next # remove it p1 = p1.next # dont step p2 else: p2 = p1 p1 = p1.next return head if __name__ == '__main__': test = SinglyLinkedList() test.insert(1) test.insert(1) test.insert(2) test.insert(3) test.insert(3) test.print_list() h = delete_duplicates(test.head) result = SinglyLinkedList() result.head = h result.print_list()