Thursday, September 5, 2013

2.4 -- partion a linked list around a value x

Q:
Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.

A:
find a pivot point,   (e.g. the first one)   and all the rest of node, whose value less than pivotValue x,  insert at head.
 private static void partitionOnPivot(LinkList list, int pivotValue) {
  // use the first node as the pivot, if the following less then
  // pivotValue, insert before, otherwise, insert after
  Node runner = null;
  Node preRunner = null;;
  if (list.head != null) {   
   preRunner = list.head;
   runner=preRunner.next;
  }
  while (runner != null) {
   if (runner.data < pivotValue) {// insert before pivotNode
    preRunner.next=runner.next; //delete runner off the list
    //insert runner at the beginning of the list
    runner.next = list.head;
    list.head = runner;
    
    //position runner 
    runner = preRunner.next;
   }else{
    preRunner = runner;
    runner = runner.next;
   }
   
  }

 }

Mistakes:
1:
对于一个LinkList类,定义为:
public class LinkList {
 Node head;
}    

  Node runner = null;
  Node preRunner = list.head;
  if (list.head != null) {   
   runner = list.head;   
  }
那么,对于一个列表为:
8 40 41 的list,
runner.data的值为什么呢??? -------------------          未定义(或者说,没有)
preRunner.data的值为什么呢?????------------------ 8

update : 上面这个问题,会造成混乱。 原因就在于,我们定义LinkList中的head时, 是把它作为一个单独的object,or a pointer pointing to the first element of the list.

以后的程序中,暂定是前者。(否则,就应该叫 firstNode)

No comments:

Post a Comment