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); }
相关文章推荐
- LeetCode—Insertion Sort List 解题报告
- LeetCode: Insertion Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- leetCode解题报告之Insertion Sort List
- 【LeetCode】Insertion Sort List 解题报告
- Leetcode Sort List 解题报告
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)
- leetcode 148. Sort List 解题报告
- LeetCode 148. Sort List 解题报告(归并排序小结)
- leetCode解题报告之Sort List
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- [leetcode] 147. Insertion Sort List 解题报告
- [leetcode] 148. Sort List 解题报告
- [Leetcode] 148. Sort List 解题报告
- LeetCode: Sort List 解题报告
- LeetCode 解题报告 Sort List
- LeetCode Sort List 解题报告
- LeetCode—Sort List解题报告
- [Leetcode] 147. Insertion Sort List 解题报告
- LeetCode Sort List 解题报告