zoukankan      html  css  js  c++  java
  • [LeetCode]Insertion Sort List

    Sort a linked list using insertion sort.

    思考:画图帮助理解,考虑以下情况:空链表,单结点链表,两个结点(第二个结点大于或小于第一个),多个结点。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *insertionSortList(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            ListNode *p,*q,*r;
    		p=head;
    		if(!head) return NULL;
    		while(p->next)
    		{
    			q=p->next;      //q当前待移动结点
    			r=head;         //r-p已排序
    			
    			while(r->next->val<q->val&&r!=p)
    				r=r->next;
    			if(r==p&&r->val<=q->val)
    			{
    				p=p->next;
    			}
    			else if(r==p)
    			{
    				r->next=q->next;
    				q->next=r;
    				head=q;
    			}
    			else if(r->val>q->val)
    			{
    				p->next=q->next;
    				q->next=r;
    				head=q;
    			}
    			else
    			{
    				p->next=q->next;
    				q->next=r->next;
    				r->next=q;
    			}
    		}
    		return head;
        }
    };
    

      

  • 相关阅读:
    这几天都是在公司慢待
    电脑没有关机可能出现发博文dns异常(write)
    DOS/VBS
    SourceInsight
    CevaEclipse
    C/C++
    Matlab
    Matlab
    C语言
    Matlab
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3423688.html
Copyright © 2011-2022 走看看