LeetCode:Insertion Sort List
2014-03-24 18:08
295 查看
这道题感觉最难的地方就在于链表节点的移动。因为链表不像数组,元素的移动很不方便,所以加了一个tmp变量,不断做循环交换来移动链表里的数组。
/** * 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* p=head->next; while(p!=NULL){ ListNode* q=head; while(q->val<p->val){ q=q->next; //找到比p指向元素“略大”的元素 } if(p!=q){ int tmp=q->val; q->val=p->val; while(p!=q){ //循环交换元素,相当于tmp一直在往链表后面移动,直到与p->next交换 q=q->next; swap(tmp,q->val); } } p=p->next; } return head; } };
相关文章推荐
- LeetCode :Insertion Sort List
- leetcode——Insertion Sort List 对链表进行插入排序(AC)
- Leetcode:Insertion Sort List
- [LeetCode]Insertion Sort List
- LeetCode 147:Insertion Sort List
- leetcode_c++:链表:Insertion Sort List(147)
- Insertion Sort List[LeetCode]
- LeetCode147—Insertion Sort List
- leetcode---insertion-sort-list---链表
- leetcode. Insertion Sort List
- LeetCode 147 — Insertion Sort List(C++ Java Python)
- LeetCode Insertion Sort List
- LeetCode 147 Insertion Sort List
- LeetCode | Insertion Sort List
- [leetcode] Insertion Sort List
- Leetcode: insertion-sort-list
- 【LeetCode】Insertion Sort List
- leetcode Insertion Sort List
- LeetCode | Insertion Sort List
- leetcode Insertion Sort List