您的位置:首页 > 编程语言 > Go语言

Insertion Sort List

2014-01-27 07:04 501 查看


Insertion Sort List

 Total Accepted: 4614 Total
Submissions: 18226My Submissions

Sort a linked list using insertion sort.

// iterator
public static ListNode insertionSortList(ListNode head){
if(head == null) return null;
ListNode temp = head;
while(temp != null){
ListNode node = temp.next;
while(node!=null){
if(node.val < temp.val){
int t = node.val;
node.val = temp.val;
temp.val = t;
}
node = node.next;
}
temp = temp.next;
}
return head;
}

// recursive
public static ListNode insertionSortList2(ListNode head){
if(head == null) return null;
ListNode temp = head.next;
while(temp!=null){
if(temp.val < head.val){
int t = temp.val;
temp.val = head.val;
head.val = t;
}
temp = temp.next;
}
insertionSortList2(head.next);
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm