static int Count(ListNode head) { int count = 0; while (head != null) { count++; head = head.Next; } return count; }
static ListNode BuildList(int[] array) { ListNode head = new ListNode() { Value = array[0] }; var current = head; for (int i = 1; i < array.Length; i++) { current.Next = new ListNode() { Value = array[i] }; current = current.Next; } return head; }
public void Add(int x) { count++; if (head == null) { head = new ListNode(x); tail = head; return; } tail.next = new ListNode(x); tail = tail.next; }
private static TreeNode DoConvert(ref ListNode head, int n) { if (n <= 0) { return null; } TreeNode left = DoConvert(ref head, n / 2); TreeNode root = new TreeNode() { Value = head.Value, Left = left }; head = head.Next; root.Right = DoConvert(ref head, n - n / 2 - 1); return root; }
private void ShuffleRecursive(ListNode head, int size) { if (size <= 1) { return; } int halfSize = size / 2; ListNode right = head; for (int i = 0; i < halfSize; i++) { right = right.next; } ShuffleRecursive(head, halfSize); ShuffleRecursive(right, size - halfSize); if (ShouldFlip() || true) { Flip(head, halfSize, right, size - halfSize); } }
private void Flip(ListNode left, int leftSize, ListNode right, int rightSize) { ListNode leftTail = left; ListNode rightTail = right; //find last element on the left for (int i = 1; i < leftSize; i++) { leftTail = leftTail.next; } //find last element on the right for (int i = 1; i < rightSize; i++) { rightTail = rightTail.next; } ListNode temp = rightTail.next; //last element of right points to first element of the left rightTail.next = left; //last element of left, points to right's old tail leftTail.next = temp; }
static TreeNode Convert(ListNode head) { int n = Count(head); return DoConvert(ref head, n); }