lintcode :链表插入排序

题目:

用插入排序对链表排序

样例

Given 1->3->2->0->null, return 0->1->2->3->null

解题:

感觉很简单,但是没有写出来,链表的操作还不行的,九章程序

Java程序:

/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
public ListNode insertionSortList(ListNode head) {
// write your code here
ListNode dummy = new ListNode(0); while (head != null) {
ListNode node = dummy;
while (node.next != null && node.next.val < head.val) {
node = node.next;
}
ListNode temp = head.next;
head.next = node.next;
node.next = head;
head = temp;
} return dummy.next;
}
}

总耗时: 2735 ms

Python程序:

"""
Definition of ListNode
class ListNode(object): def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def insertionSortList(self, head):
# write your code here
if head == None:
return head
p = ListNode(0)
while head!=None:
node = p
while node.next!=None and node.next.val<head.val:
node = node.next
tmp = head.next
head.next = node.next
node.next = head
head = tmp
return p.next
上一篇:Ajax禁止缓存的几个解决方案


下一篇:string