您的位置:首页 > 其它

Insertion Sort List

2014-11-24 23:02 239 查看

Insertion Sort List

Sort a linked list using insertion sort.

这道题用两个链表做的,这样方便一点。还有新链表头结点我没有存放内容,这样也比较方便,后面返回head1.next就好了

/**
* 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) {
ListNode head1 = new ListNode(0);
if(null == head || null == head.next)
return head;

else{
ListNode temp = new ListNode(0);
temp.val = head.val;
temp.next = null;
head1.next = temp;//用一个新链表

ListNode ptr = head.next;
while(ptr != null){        //遍历原来的链表,插入到新链表中
temp = head1.next;
ListNode tempPre = head1;            //temp前面的节点
while(temp != null){
if(temp.val > ptr.val){            //在temp前面插入结点
ListNode nodeAdd = new ListNode(0);
nodeAdd.val = ptr.val;
nodeAdd.next = temp;
tempPre.next = nodeAdd;
break;                        //插入完成,跳出循环
}
temp = temp.next;
tempPre = tempPre.next;
}
if(null == temp){                    //在新链表添加节点
ListNode nodeAdd = new ListNode(0);
nodeAdd.val = ptr.val;
nodeAdd.next = null;
tempPre.next = nodeAdd;
}
ptr = ptr.next;
}
}

return head1.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: