问题如下:
Sort a linked list using insertion sort.
在eclipse上:
定义节点类:
package leetcode5.InsertSortLink;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
解决问题类:
package leetcode5.InsertSortLink;
public class Solution {
public ListNode InserionSortLink(ListNode head){
if (head==null || head.next==null)//判断是否为空 或只有一个头指针
return head;
ListNode l=head;
ListNode cur=null;
while(l.next!=null){
cur=l.next;
if(cur.val>=l.val){//当前的顺序正确,返回继续循环
l=l.next;
continue;
}
l.next=cur.next;
//now cur.val<l.val;
if(cur.val<=head.val){//直接与头指针比较
cur.next=head;
head=cur;
continue;
}
ListNode pos=findPos(head,cur);//找到插入位置
cur.next=pos.next;//插入
pos.next=cur;
}
return head;
}
public ListNode findPos(ListNode head,ListNode l){//头指针与当前指针之间找到插入位置
ListNode pos=head;
while(head!=null&&head.val<l.val){
pos=head;
head=head.next;
}
return pos;
}
}
总结:首先考虑特殊情况,即只有头节点与头节点为空的情况,其次,进行插入排序,如果正序,则指针继续向下遍历,如果不正序,则先与头节点比较,比头节点小则直接插入到头节点之前,否则利用其他方法寻找到适当的插入位置(从头节点开始遍历,因为此时从头节点开始到插入节点之间是有序的,寻找到插入位置)
很赞的插入方法... 应学习
参考博文来自:http://blog.csdn.net/lilong_dream