def add_depend_reverse(head1, head2): """ 利用链表翻转实现链表节点值相加 :type head1:Node :type head2:Node :param head1: :param head2: :return: """ head1_reverse = head1.reverse() head2_reverse = head2.reverse() carry = 0 result = None while head1_reverse or head2_reverse: h1 = head1_reverse.value if head1_reverse else 0 h2 = head2_reverse.value if head2_reverse else 0 sun = carry + h1 + h2 carry = math.floor(sun / 10) node = result result = Node(sun % 10) result.next = node head1_reverse = head1_reverse.next if head1_reverse else None head2_reverse = head2_reverse.next if head2_reverse else None # 最后可能有进位 if carry: node = result result = Node(1) result.next = node return result
def test_property_setter_next(self): next_node = Node(2) node = Node(1) node.next = next_node self.assertEqual(id(node.next), id(next_node)) with self.assertRaises(TypeError): node.next = 1
def test_for_multiple_nodes(self): node2 = Node(2) node1 = Node(1, node2) self.assertIsNone(node2.next()) node1.append(3) self.assertIsNotNone(node2.next(), None) self.assertEqual(node2.next().value(), 3)
def add_depend_list(head1, head2): """ 利用列表(栈)实现链表节点值相加 :type head1:Node :type head2:Node :param head1: :param head2: :return: """ head1_list = [] head2_list = [] while head1: head1_list.append(head1.value) head1 = head1.next while head2: head2_list.append(head2.value) head2 = head2.next carry = 0 result = None while head1_list or head2_list: h1 = head1_list.pop() if head1_list else 0 h2 = head2_list.pop() if head2_list else 0 sun = h1 + h2 + carry node = result result = Node(sun % 10) result.next = node carry = math.floor(sun / 10) # 最后可能有进位 if carry: node = result result = Node(1) result.next = node return result
def test_add_last_in_list(self): head = Node(123) to_be_last_node = Node(555) head.next = to_be_last_node to_be_last_node.next = Node(7656) self.linked_list.head = head self.helper.helper_add_last_in_list(self.linked_list, to_be_last_node)
def test_delete_node_after_head(self): head = Node(6) after_node = Node(100) node_to_delete = Node(8528) head.next = node_to_delete node_to_delete.next = after_node self.helper.helper_delete_node_after_head(self.linked_list, head, node_to_delete)
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 ll_1(): el1 = Node(3) el2 = Node(4) el3 = Node(5) el4 = Node(8) el1.next = el2 el2.next = el3 el3.next = el4 el4.next = None return LinkedList(el1)
def insert_before(self, index, value): newnode = Node(value) if index == 0: newnode.next = self.head_node if self.head_node == None: # insert_before(0,*) should still work on an empty list self.tail_node = newnode self.head_node = newnode else: node = self.get_node_by_index(index - 1) newnode.next = node.next node.next = newnode self.list_length += 1
def ll_cycle(): el1 = Node(2) el2 = Node(4) el3 = Node(8) el4 = Node(11) el1.next = el2 el2.next = el3 el3.next = el4 el4.next = el2 return LinkedList(el1)
def test_delete_node_after_head(self): head = Node(6) after_node = Node(100) node_to_delete = Node(8528) head.next = node_to_delete node_to_delete.prev = head node_to_delete.next = after_node after_node.prev = node_to_delete self.helper.helper_delete_node_after_head(self.linked_list, head, node_to_delete) self.assertEqual(after_node.prev, head)
def testNext(self): node = Node(data="data",next=None) first_node = Node(data="first",next=node) self.assertEqual(first_node.next,node) third = Node(data="third",next=None) node.next = third self.assertEqual(node.next,third)
def insert(self, item_new, pos): """given an item and a position, this method insert an item at the position required""" actual_position = 0 previous_position = None current = self.head new_node = Node(None, item_new) while actual_position != pos and current is not None: previous_position = current current = current.next actual_position += 1 if actual_position != pos: raise ValueError("Invalid Position %d" % pos) previous_position.next = new_node new_node.next = current new_node.previous = previous_position if current is None: self.tail = new_node else: current.previous = new_node return self
def add_numbers(node_1, node_2): """Recursive math is delightful.""" # First, get the next nodes for node_1 and node_2 if node_1 is not None: next_1 = node_1.next next_2 = node_2.next # Computer the value for the next step to build up result_node, carryover = add_numbers(next_1, next_2) # Sum the two values and the carryover sum_value = node_1.data + node_2.data + carryover # Take the modulo 10 number and assign it to digit digit = sum_value % 10 # Flat divide by ten and assign that to carryover carryover = sum_value // 10 # Create our new node with the digit new_node = Node(digit) # Assign the result of the next step as the next node new_node.next = result_node return (new_node, carryover) # End of the list, recursion stops else: return (None, 0)
def test_find_loop_start(self): print('Test: Empty list') linked_list = MyLinkedList() assert_equal(linked_list.find_loop_start(), None) print('Test: Not a circular linked list: One element') head = Node(1) linked_list = MyLinkedList(head) assert_equal(linked_list.find_loop_start(), None) print('Test: Not a circular linked list: Two elements') linked_list.append(2) assert_equal(linked_list.find_loop_start(), None) print('Test: Not a circular linked list: Three or more elements') linked_list.append(3) assert_equal(linked_list.find_loop_start(), None) print('Test: General case: Circular linked list') node10 = Node(10) node9 = Node(9, node10) node8 = Node(8, node9) node7 = Node(7, node8) node6 = Node(6, node7) node5 = Node(5, node6) node4 = Node(4, node5) node3 = Node(3, node4) node2 = Node(2, node3) node1 = Node(1, node2) node0 = Node(0, node1) node10.next = node3 linked_list = MyLinkedList(node0) assert_equal(linked_list.find_loop_start(), node3) print('Success: test_find_loop_start')
def test_node_set_next(): first_node = Node(4) second_node = Node(5) first_node.next = second_node assert first_node.next.data == 5
def testNext(self): node = Node(data="data", next=None) first_node = Node(data="first", next=node) self.assertEqual(first_node.next, node) third = Node(data="third", next=None) node.next = third self.assertEqual(node.next, third)
def add_forward(node1, node2): if not node1 and not node2: return (None, 0) next, carry = add_forward(node1.next, node2.next) q, r = divmod(node1.value + node2.value + carry, 10) node = Node(r) node.next = next return (node, q)
def insert_after(self, index, value): node = self.get_node_by_index(index) newnode = Node(value) newnode.next = node.next node.next = newnode if newnode.next == None: self.tail_node = newnode self.list_length += 1
def reverse_and_clone(node): head = None while node != None: new_node = Node(node.data) new_node.next = head head = new_node node = node.next return head
def push(self, data): node = Node(data) if self.top is None: self.top = node self.size = self.size + 1 else: node.next = self.top self.top = node self.size = self.size + 1
def push(self, data): node = Node(data) if not self._head: self._head = node else: node.next = self._head self._head = node self._size += 1
def linked_list_intro_play(self): """ Linked List | Set 1 (Introduction)""" # Steps are: # 1. Create an empty list # 2. Create nodes # 3. Link the nodes. # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) ''' Three nodes have been created. We have references to these three blocks as first, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' llist.head.next = second # Link first node with second ''' Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ ''' second.next = third # Link second node with the third node ''' Now next of second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ ''' # traversing the entire linked list and printing llist.print_list()
def delete_node(node: Node) -> None: ''' Overwrite each value of a linked list, starting from the node we are given to delete. ''' while node.next != None: node.val = node.next.val if node.next.next == None: node.next = None else: node = node.next
def reverseList(head: Node) -> Node: if head == None or head.next == None: return head # reversed_list = 뒤집어진 리스트의 Head node reversed_list = reverseList(head.next) head.next.next = head head.next = None return reversed_list
def insert_in_sorted_list(node, item): previous = None current = node.head stop = False while current != None and not stop: if current.data > item: stop = True else: previous = current current = current.next temp = Node(item) if previous == None: temp.next = node.head node.head = temp else: temp.next = current previous.next = temp
def insert_at_middle(head, data, position): temp = head pos = 0 while temp.next: old_node = temp new_node = temp.next temp = temp.next pos += 1 if position == pos: node_to_insert = Node(data) old_node.next = node_to_insert node_to_insert.next = new_node
def test_llist_init_str_repr(llist): first_node = Node(1) second_node = Node('a') assert str(llist) == 'None' assert repr(llist) == 'LinkedList()' llist.head = first_node first_node.next = second_node assert str(llist) == '1 -> a -> None' assert repr(llist) == 'LinkedList(1, a)' llist = LinkedList([2, 'b']) assert str(llist) == '2 -> b -> None' assert repr(llist) == 'LinkedList(2, b)'
def reverse(linked_list): # HINT: Create New Nodes pre_node = None reversed_linked_list = LinkedList() for value in linked_list: new_node = Node(value) new_node.next = pre_node pre_node = new_node reversed_linked_list.head = pre_node return reversed_linked_list
def add_reversed(node1, node2, carry): if not node1 and not node2 and carry == 0: return sum = carry if node1: sum += node1.value if node2: sum += node2.value q, r = divmod(sum, 10) node = Node(r) node.next = add_reversed(node1.next if node1 else None, node2.next if node2 else None, q) return node
def delete_n_th_reversed(head: Node, n: int): sentinel = Node(0) sentinel.next = head p = sentinel q = sentinel for _ in range(n + 1): p = p.next while p: p = p.next q = q.next q.next = q.next.next return sentinel.next
def reverse_2(head: Node): """ 递归 :param head: :return: """ # 找到最后一个节点 if head.next is None or head is None: return head new_head = reverse_2(head.next) head.next.next = head head.next = None return new_head
def solution2(head1, head2): # If linked lists have different lengths, pad with 0s len1, len2 = length(head1), length(head2) if len1 < len2: head1 = pad_with_zeros(head1, len2-len1) elif len1 > len2: head2 = pad_with_zeros(head2, len1-len2) # Now that the linked lists are of equal size, add them head, carry = add_forward(head1, head2) if carry != 0: node = Node(carry) node.next, head = head, node # insert at front return head
def pad_with_zeros(head, count): for i in range(count): node = Node(0) node.next, head = head, node # insert at front return head
def test_node_str_representation_with_next(self): n = Node(9) n.next = Node('X') self.assertEqual(str(n), "Node(9) > Node(X)")
if length == 1: return node.next if length == 2: if node.value == node.next.value: return node.next.next else: return -1 last_node = visit(node.next, length-2) if last_node != -1: if node.value == last_node.value: return last_node.next return -1 def palindrome(head): length = 0 node = head while node: length += 1 node = node.next print visit(head, length) head = Node('r') head.next = Node('a') head.next.next = Node('d') head.next.next.next = Node('a') head.next.next.next.next = Node('r') palindrome(head) # None if palindrome, -1 otherwise
prev= None current = n1 while current!=None: right = current.next current.next = prev prev = current current = right return prev def printList(n): while n!= None: print n.value n = n.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 = None printList(n1) nret = reverse(n1) print nret.value printList(nret)
from linked_list import Node acyclic = Node(1, Node(2, Node(3))) cyclic = Node(1) cyclic.next = Node(2, Node(3, Node(4, cyclic))) def node_generator(node): while node: yield node node=node.next def is_cyclic(node): faster_generator = node_generator(node) slower_generator = node_generator(node) try: next(faster_generator) for item in slower_generator: #item = 3 item0 = next(faster_generator) # item0 = 2 item1 = next(faster_generator) # item1 = 3 if id(item) == id(item0) or id(item) == id(item1): return True except StopIteration: pass return False print(is_cyclic(acyclic)) print(is_cyclic(cyclic))