//method 1, make a small list and large list, then merge them (small.next = large.head). O(N) time, O(1) space static LinkListNode partition(LinkListNode head, int d) { LinkListNode s = null; LinkListNode sHead = null; LinkListNode l = null; LinkListNode lhead = null; LinkListNode n = head; while (n != null) { LinkListNode next = n.next; n.next = null; //otherwise stack overflow exception if (n.data < d) { if (s == null) { sHead = n; s = sHead; } else { s.next = n; s = n; } } else { if (l == null) { lhead = n; l = lhead; } else { l.next = n; l = n; } } n = next; } if (s == null) { return(lhead); } else { s.next = lhead; return(sHead); } }
public void setNext(LinkListNode n) { next = n; if (this == last) { last = n; } if (n != null && n.prev != this) { n.setPrevious(this); } }
public LinkListNode clone() { LinkListNode next2 = null; if (next != null) { next2 = next.clone(); } LinkListNode head2 = new LinkListNode(data, next2, null); return(head2); }
{//Partition: Write code to partition a linked list around value x, such that all nodes less than x come before all nodes greater than or equal to x. //If x is contained within the list, the values of x only need to be after the elements less than x. static void Main(string[] args) { int[] intArray = new int[] { 3, 5, 8, 5, 10, 2, 1 }; LinkListNode first = new LinkListNode(intArray[0]); LinkListNode head = first; for (int i = 1; i < intArray.Length; i++) { LinkListNode second = new LinkListNode(intArray[i]); first.next = second; first = second; } Console.WriteLine(head.printForward()); LinkListNode newHead = partition2(head, 5); Console.WriteLine(newHead.printForward()); }
public LinkListNode(int d, LinkListNode n, LinkListNode p) { data = d; setNext(n); setPrevious(p); }