您的位置:首页 > 编程语言 > Java开发

[LeetCode] Insertion Sort List

2014-08-18 15:25 357 查看
Insertion Sort List Total Accepted: 18506 Total Submissions: 73505 My Submissions
Sort a linked list using insertion sort.

链表的插入排序,没什么难度,注意边界条件

/**
*
* 插入排序链表
* @author zhouyf
*
*/
public class InsertionSortList {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}

public ListNode insertionSortList(ListNode head) {
if (head == null) {
return null;
}

if (head.next == null) {
return head;
}
ListNode newHead = head;

ListNode curNode = head.next;
ListNode curPreNode = head;

while (curNode != null) {
ListNode pNode = newHead;
ListNode preNode = null;

while (pNode != curNode) {
if (curNode.val < pNode.val) {
if (preNode == null) {
ListNode oldHead = newHead;
newHead = curNode;
curPreNode.next = curNode.next;
curNode.next = oldHead;
} else {
ListNode old = curNode.next;
curNode.next = preNode.next;
preNode.next = curNode;
curPreNode.next = old;
}
curNode = curPreNode.next;
break;
} else {
preNode = pNode;
pNode = pNode.next;
}
}

if (pNode == curNode) {
curPreNode = curNode;
curNode = curNode.next;
}
}

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