[LeetCode] Insertion Sort List

Sort a linked list using insertion sort.

 

对于指针链表类题,分析时一定要用笔先清晰画出来,每个指针对应那些结点。

对比:

(1)插入排序的顺序表实现,是对temp从参考点temp往前与一个个元素比较,

(2)插入排序的链表实现,是对temp从头结点开始往后与一个个元素比较。(因为链表只有next域,如果像顺序表一样往前比较代码会比较麻烦)

 

插入排序用顺序表实现如下所示:

void InsertSort(int a[],int n)
{
   int i,j;
   int temp;
   for(i=0;i<n-1;i++)
   {
      temp = a[i+1];
      j = i;
      while(j>-1 && temp <a[j])
      {
         a[j+1]=a[j];
         j--;
      }
      a[j+1] = temp;
   }
}

插入排序用链表实现如下所示:

  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };


class Solution 
{
public:
    ListNode *insertionSortList(ListNode *head) 
    {
        if(head == NULL)
            return NULL;
        ListNode *pi ,*temp = head->next; //temp是参考点,即要插入的值的结点。
        ListNode *forehead = new ListNode(0);
        forehead->next = head;
            
        

        while(temp != NULL)
        {
            ListNode *pi0 = forehead;
            pi = forehead->next;    //不能写pi = head,因为head还是原先的head,这里的head有可能已经变了
            while(pi != temp && pi->val < temp->val)
           {
             pi0 = pi;
             pi = pi->next;
           }
           
           ListNode *temp1 = temp;
           temp = temp->next;

           if(pi != temp1)    //此时temp1是参考点,把它插入该插入的位置
          {
              pi0->next = temp1;
              temp1->next = pi;
              while(pi->next  != temp1) 
                   pi = pi->next;
              pi->next = temp;
          }
               
        }
        return forehead->next;
    }
};

 

posted @ 2014-06-09 11:33  Xylophone  Views(139)  Comments(0Edit  收藏  举报