def reverse_LinkedList(ll): node1 = ll.start node2 = ll.start.next node1.next = None while node2 != None: node3 = node2.next node2.next = node1 node1 = node2 node2 = node3 return LinkedList(node1)
def swapPairs(head): node = head if node == None: return node if node.next == None: return node new_head = node.next while True: if node.next == None: break n1 = node.next n2 = node.next.next n1.next = node if n2 == None: node.next = None break if n2.next == None: node.next = n2 else: node.next = n2.next node = n2 return new_head l1 = LinkedList([1,2,3,4,5,6]).start l2 = swapPairs(l1) l2.print()
return new_head def reverse_next_K(l1, k): node = l1 head = node n1 = node.next n2 = n1.next node.next = None for i in range(k - 1): print('node:', node.val) n1.next = node if n2 == None: return head, n1 node = n1 n1 = n2 n2 = n2.next head.next = n1 return head, node a = [k for k in range(1, 6)] l1 = LinkedList(a) l1.print() l = l1.start s = reverseKGroup(l, 3) print('s:') s.print()
# even = even.next # node = node.next # id += 1 # return head def oddEvenList(head): if head == None or head.next == None or head.next.next == None: return head n1 = head n2 = head.next while n2 != None and n2.next != None: node = n2.next n2.next = n2.next.next n3 = n1.next n1.next = node node.next = n3 n1 = n1.next n2 = n2.next return head a = LinkedList([1, 2, 3, 4, 5, 6, 7, 8, 9]).start oddEvenList(a) print(a) h = a while h != None: print(h.val) h = h.next
from _LinkedList import Node, LinkedList def detectCycle(head): if head == None: return end = Node('END') while head.next != None: if head.next.val == 'END': return head node = head.next head.next = end head = node return l = LinkedList([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) n2 = l.get_Node(2) n9 = l.get_Node(l.length - 1) n9.next = n2 n0 = l.start print(detectCycle(n0))
else: start = n1 n1 = n1.next n = start while n1 != None: print('n:', n.val, 'n1:', n1.val, 'n2:', n2.val) if n2 != None: if n1.val > n2.val: n.next = n2 n2 = n2.next else: n.next = n1 n1 = n1.next n = n.next else: n.next = n1 n1 = n1.next return start n.next = n2 return start L1 = LinkedList([2]).start L2 = LinkedList([1]).start s = mergeTwoLists(L1, L2) while s != None: print(s.val) s = s.next
import numpy as np from _LinkedList import Node, LinkedList def reverse_LinkedList(ll): node1 = ll.start node2 = ll.start.next node1.next = None while node2 != None: node3 = node2.next node2.next = node1 node1 = node2 node2 = node3 return LinkedList(node1) l = np.random.randint(8, size=20) ll1 = LinkedList(l) ll1.print() ll2 = reverse_LinkedList(ll1) ll2.print()