您的位置:首页 > 其它

leetcode笔记--Insertion Sort List

2016-02-19 18:50 423 查看
题目:难度(Medium)

Sort a linked list using insertion sort.

Tags:Linked List Sort

Similar Problems:(M) Sort List

分析:使用插入排序进行排序,插入排序:直接插入排序O(n2)、折半插入排序O(n2)、希尔排序O(nlogn)、归并排序O(nlogn)

我采用直接插入排序。该算法的基本操作是:将一个记录插入到已经排好序的有序表中,从而得到一个新的、记录数增1的有序表

初始时,第一个记录可看成是一个有序表,然后从第二个记录起逐个插入,直至整个序列按关键字非递减排列

为方便操作,为排好序的链表装上一个“头节点”

代码实现:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head

#为方便操作,为排好序的链表装上一个“头节点”
head1 = ListNode(0)
#head1.next = None
q = head
#q为当前要插入的元素
while q is not None:
#注意:在insertInToSortedList的第2个参数node即此循环中的q,由于insertInToSortedList的最后一句node.next = q
#改变的node.next的指向即本循环中q.next的指向,所以必须先记录下本循环中q的指向,以防丢失q的指向
#故在此添加node = q q = q.next语句,否则会报错
node = q
q = q.next
head1 = self.insertInToSortedList(head1, node)
return head1.next

#向带有头节点的有序表中插入一个节点
def insertInToSortedList(self, head, node):
p = head
q= head.next
while q is not None:
if q.val > node.val:
break
else:
p = q
q = q.next
#此时p指向要插入的位置的前驱,q为要插入位置的后继
p.next = node
node.next = q
return head
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: