LeetCode----Insertion Sort List
2015-11-14 17:16
393 查看
Insertion Sort List
Sort a linked list using insertion sort.
分析:
使用插入排序对链表进行排序。
可以新建一个带头节点的有序链表,每次从原链表中选择一个节点,插入到带头节点的链表中。
C++代码:
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode dummy = ListNode(-1);
ListNode * cur = head, *p, *pnext, *t;
while(cur){
p = &dummy;
while(p->next && cur->val > p->next->val){
p = p->next;
}
pnext = p->next;
p->next = cur;
t = cur->next;
cur->next = pnext;
cur = t;
}
return dummy.next;
}
};
Python的代码不知道为什么一直TLE。
先贴上,等回头再过来改。
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
cur = head
# dummy是新的链表表头
dummy = ListNode(-1)
while cur:
p = dummy
while p.next and cur.val > p.next.val:
p = p.next
pNext = p.next
p.next = cur
t = cur.next
cur.next = pNext
cur = t
return dummy.next
Sort a linked list using insertion sort.
分析:
使用插入排序对链表进行排序。
可以新建一个带头节点的有序链表,每次从原链表中选择一个节点,插入到带头节点的链表中。
C++代码:
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode dummy = ListNode(-1);
ListNode * cur = head, *p, *pnext, *t;
while(cur){
p = &dummy;
while(p->next && cur->val > p->next->val){
p = p->next;
}
pnext = p->next;
p->next = cur;
t = cur->next;
cur->next = pnext;
cur = t;
}
return dummy.next;
}
};
Python的代码不知道为什么一直TLE。
先贴上,等回头再过来改。
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
cur = head
# dummy是新的链表表头
dummy = ListNode(-1)
while cur:
p = dummy
while p.next and cur.val > p.next.val:
p = p.next
pNext = p.next
p.next = cur
t = cur.next
cur.next = pNext
cur = t
return dummy.next
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 插入排序
- 关于指针的一些事情
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定