您的位置:首页 > 其它

LeetCode---Insertion Sort List

2014-08-13 20:21 357 查看
LeetCode---Insertion Sort List
题目:Sort a linked list using insertion sort.

题目说的很清楚,对单链表使用插入排序方法进行排序。
先把代码贴出来然后说一下哪块需要注意吧。(已AC)
#include <iostream>
using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode *insertionSortList(ListNode *head)
{
if (!head || head->next == NULL)
{
return head;
}

ListNode* cur = head;
ListNode* pos = head->next;
cur->next = NULL;
while(pos != NULL)
{
bool isinsert = false;
while(cur->next != NULL)
{
if (cur->val > pos->val)
{
ListNode* temp = pos;
pos = pos->next;

temp->next = cur->next;
cur->next = temp;

int temp_val = cur->val;
cur->val = temp->val;
temp->val = temp_val;

isinsert = true;
cur = head;
break;
}
else
{
cur = cur->next;
}
}
if (!isinsert && cur->next == NULL)
{
ListNode* temp = pos;
pos = pos->next;

temp->next = cur->next;
cur->next = temp;
if (cur->val > temp->val)
{
int temnum = cur->val;
cur->val = temp->val;
temp->val = temnum;
}
cur = head;
}
}
return head;
}
};

int main()
{
ListNode* first = new ListNode(1);
ListNode* second = new ListNode(3);
ListNode* third = new ListNode(2);
ListNode* forth = new ListNode(4);
ListNode* five = new ListNode(5);
first->next = second;
second->next = third;
third->next = forth;
forth->next = five;

Solution sol;
ListNode*ret = sol.insertionSortList(first);

return 0;
}


主要有以下几种情况:
1、链表为空或者只有一个元素,则直接返回。
2、ListNode* cur = head;//当前排好序的链表直接指向头结点,即直接将待排序列表中第一个元素当做已排序链表的第一个结点。

ListNode* pos = head->next;//记录下一个待排序的结点。

cur->next = NULL;//将第一个结点的next置为空,这样我们就有了两个链表(第一个是以head为头结点的链表,第二个是以pos为头结点的链表)
3、while(pos != NULL) 保证pos不为空,while(cur->next!=
NULL)保证除了最后一个排好序的节点,其他结点都与pos指向的结点做比较
4、通过使用cur指针将已排好序的列表元素从头开始与当前pos指的元素进行比较。此处使用的bool isinsert = false;变量,是用来控制当前的pos所指的元素是否已经和排好序中的元素进行了插入操作。如果cur遍历到了已排好序链表的最后一个元素,此时isinsert变量值还是为false则表明,当前的结点就差与已排好序的最后一个结点进行比较了,然后做比较处理(此处我先做了插入再进行值的比较和替换,个人觉得效果和比较完了再插入稍微简单点)。当在内循环需要做插入操作时,isinsert变量值为true,表示此结点已经被计算过了,不用再继续循环了,将cur指向head,跳出内循环,继续比较下一个结点。
5、当pos为空跳出循环,表明已经对原始链表中的所有结点进行了插入排序响应操作,此时返回head,改链表便被排好序了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: