您的位置:首页 > 编程语言 > C语言/C++

LeetCode 147 — Insertion Sort List(C++ Java Python)

2014-02-27 21:03 579 查看
题目:http://oj.leetcode.com/problems/insertion-sort-list/

Sort a linked list using insertion sort.

题目翻译:

使用插入排序对链表进行排序。

分析:

        注意细节。

C++实现:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == NULL || head->next == NULL)
{
return head;
}

ListNode *node = head;
ListNode *cur = NULL;

while(node->next != NULL)
{
cur = node->next;

if(cur->val >= node->val)
{
node = node->next;
continue;
}

node->next = cur->next;

if(cur->val <= head->val)
{
cur->next = head;
head = cur;
continue;
}

ListNode *pos = findInsertPos(head, cur);

cur->next = pos->next;
pos->next = cur;
}

return head;
}

ListNode *findInsertPos(ListNode *head, ListNode *node)
{
ListNode *pos = head;
while(head != NULL && head->val < node->val)
{
pos = head;
head = head->next;
}

return pos;
}
};

Java实现:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}

ListNode node = head;
ListNode cur = null;

while (node.next != null) {
cur = node.next;

if (cur.val >= node.val) {
node = node.next;
continue;
}

node.next = cur.next;  // delete the node

if (cur.val <= head.val) {
cur.next = head;
head = cur;
continue;
}

ListNode pos = findInsertPos(head, cur);

cur.next = pos.next;
pos.next = cur;
}

return head;
}

ListNode findInsertPos(ListNode head, ListNode node) {
ListNode pos = head;
while (head != null && head.val < node.val) {
pos = head;
head = head.next;
}

return pos;
}
}

Python实现:

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

class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if head == None or head.next == None:
return head

node = head;

while node.next != None:
cur = node.next

if cur.val >= node.val:
node = node.next
continue

node.next = cur.next

if cur.val <= head.val:
cur.next = head
head = cur
continue

pos = self.findInsertPos(head, cur)

cur.next = pos.next
pos.next = cur

return head

def findInsertPos(self, head, node):
pos = head
while head != None and node.val > head.val:
pos = head
head = head.next

return pos

        感谢阅读,欢迎评论!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息