public void alternateSplit(Node head) { if (null == head || null == head.next) return; Node current = head.next.next; Node head1 = head; Node head2 = head.next; head1.next = null; head2.next = null; boolean first = true; while (current != null) { if (first) { Node temp = current.next; current.next = null; head1 = Push.pushNode(head1, current); first = false; current = temp; } else { Node temp = current.next; current.next = null; head2 = Push.pushNode(head2, current); first = true; current = temp; } } head1 = ReverseListIterative.reverse(head1); head2 = ReverseListIterative.reverse(head2); System.out.println("List1: "); PrintLinkedList.print(head1); System.out.println(); System.out.println("List2: "); PrintLinkedList.print(head2); }
public static void main(String[] args) { Node node = new Node(6); node = Push.push(node, 4); node = Push.push(node, 9); node = Push.push(node, 5); node = Push.push(node, 7); Node node1 = new Node(4); node1 = Push.push(node1, 8); System.out.println("Number1: "); PrintLinkedList.print(node); System.out.println(); System.out.println("Number2: "); PrintLinkedList.print(node1); System.out.println(); System.out.println("Sum: "); PrintLinkedList.print(new AddTwoNumbers().addNumbers(node, node1)); }
public static void main(String[] args) { Node node = new Node(40); node = Push.push(node, 30); node = Push.push(node, 20); node = Push.push(node, 10); node = Push.push(node, 5); PrintLinkedList.print(node); System.out.println(); AlternatingSplit altSplit = new AlternatingSplit(); altSplit.alternateSplit(node); }
// using Floyd’s Cycle-Finding Algorithm O(n) public boolean detect2(Node head) { if (null == head) return false; Node pointer1 = head; Node pointer2 = head; while (null != pointer2 && null != pointer1.next && null != pointer1.next.next) { pointer1 = pointer1.next.next; pointer2 = pointer2.next; if (pointer1 == pointer2) { PrintLinkedList.print(removeLoop(pointer1, head)); return true; } } return false; }