您的位置:首页 > 其它

Insertion Sort List

2014-01-06 11:16 232 查看
Sort a linked list using insertion sort.

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public 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.
if(head == null) return null;
ListNode curNode = null;
ListNode preNode=null;
ListNode nextNode=null;
ListNode node = null;
curNode = head.next;
head.next = null;
while(curNode!=null)//当前要插入的节点
{
node = curNode.next;//保存下一个节点
if(curNode.val < head.val)//比头结点还小,则成为新的头结点
{
curNode.next = head;
head = curNode;
}
else
{
preNode = head;
nextNode = head.next;
while(nextNode!=null && nextNode.val<curNode.val)//找到合适位置
{
preNode = nextNode;
nextNode = nextNode.next;
}
curNode.next = preNode.next;
preNode.next = curNode;
}
curNode = node;
}
return head;//返回新的头结点
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: