您的位置:首页 > 其它

Leetcode Insertion Sort List 解题报告

2014-08-15 06:36 405 查看
LinkedList的insertion sort和array的一样,不过指针插入操作需要想清楚。熟能生巧,还是没到很快就写对的程度。

#include <iostream>
using namespace std;

/**
* Definition for singly-linked list.
*/

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

void printList(ListNode *head)
{
while (head)
{
cout<<head->val<<"\t";
head = head->next;
}
cout<<endl;
}

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

ListNode *pp, *p, *pq = head, *q = head->next;
while (q)
{
pp = NULL;
p = head;
while (p->val <= q->val && p != q)
{
pp = p;
p = p->next;
}
if (p == q)
{
pq = q;
q = q->next;
}
else
{
if (pp)
{
pp->next = q;
q = q->next;
pq->next = q;
pp->next->next = p;
}
else
{
head = q;
pp = q;
q = q->next;
pp->next = p;
pq->next = q;
}
}
}

return head;
}
};

int main()
{
int nums[] = {4,19,14,5,-3,1,8,5,11,15};
int n = sizeof(nums) / sizeof(int);
ListNode *head = NULL, *tail = NULL;
for (int i = 0; i < n; ++i)
{
if (head == NULL)
{
head = new ListNode(nums[i]);
tail = head;
}
else
{
tail->next = new ListNode(nums[i]);
tail = tail->next;
}
}
// ListNode *head = new ListNode(4);
// head->next = new ListNode(3);
// head->next->next = new ListNode(2);
// head->next->next->next = new ListNode(1);
cout<<"before: ";
printList(head);
Solution s;
head = s.insertionSortList(head);
cout<<"after: ";
printList(head);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: