def reverse(head): new_head = None p = head while p is not None: node = Node(p.data) node.next = new_head new_head = node p = p.next return new_head
def insert(self, item: Any) -> None: self._size += 1 new_node = Node(item) if self.last is None: self.head = new_node else: self.last.next = new_node self.last = new_node
def partition_linkedlist(L, x): """ Time = O(n), Space = O(n) """ node_x = Node(x) head = tail = node_x curr = L.head while curr is not None: temp = Node(curr.data) if curr.data < x: temp.next = head head = temp else: tail.next = temp tail = temp curr = curr.next L.head = head L.remove(x)
def add(N1, N2, carry): # we are done if both lists are null and the carry value is 0 if N1 is None and N2 is None and carry == 0: return None result = Node(0) # add value and the data from L1 and L2 value = carry if N1 is not None: value += N1.data if N2 is not None: value += N2.data result.data = value % 10 # recurse if N1 is not None or N2 is not None: more = add(N1.next if N1 is not None else None, N2.next if N2 is not None else None, 1 if value >= 10 else 0) result.next = more return result
def test_is_palindrome(): a = Node(1, Node(2, Node(3, Node(2, Node(1, None))))) print_linkedlist(a) print(is_palindrome(a)) a = Node(1, Node(2, Node(2, Node(1, None)))) print_linkedlist(a) print(is_palindrome(a)) a = Node(1, Node(2, Node(3, Node(3, Node(1, None))))) print_linkedlist(a) print(is_palindrome(a))
def test_reverse(): a = Node(1, Node(2, Node(3, Node(4, None)))) b = reverse(a) print_linkedlist(b)
def insert_before(N, data): node = Node(data) node.next = N return node