标签:过程 link 问题 第一个 ret 数字 题目 push class
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *sortList(ListNode *head) { vector<int> res; ListNode *temp = head; int length = 0; while (temp){ res.push_back(temp->val); temp = temp->next, length++; } sort(res.begin(), res.end()); temp = head; int i =0; while (temp && i<length){ temp->val = res[i]; temp = temp->next; i++; } return head; } };
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *sortList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode* dummyhead = new ListNode(0); ListNode* pre = dummyhead; ListNode* cur = head; while(cur != NULL) { ListNode* next = cur->next; //维护链表的下一个结点 pre = dummyhead; //重置pre为新链表头开始 //在当前排好的新链表中找到第一个大于cur->val的结点 while(pre->next != NULL && pre->next->val <= cur->val) { pre = pre->next; } //当前pre的next结点的值大于cur的值,将cur插入到pre后 cur->next = pre->next; pre->next = cur; cur = next; //cur指向原链表的下一个节点 } return dummyhead->next; } };
标签:过程 link 问题 第一个 ret 数字 题目 push class
原文地址:http://www.cnblogs.com/Kobe10/p/6366356.html