[leetcode] Insertion Sort List
2014-07-07 09:44
267 查看
Sort a linked list using insertion sort.
思路:设立两个指针,当前指针和插入位置指针,当发现当前指针比插入位置值要小时,将两者的val交换,并且依次将插入位置指针的val往后推
输入示例:
4
4 3 2 1
代码参考了http://blog.csdn.net/doc_sgl/article/details/16343071
代码:
思路:设立两个指针,当前指针和插入位置指针,当发现当前指针比插入位置值要小时,将两者的val交换,并且依次将插入位置指针的val往后推
输入示例:
4
4 3 2 1
代码参考了http://blog.csdn.net/doc_sgl/article/details/16343071
代码:
#include<iostream> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x):val(x),next(NULL){} }; ListNode *insertionSortList(ListNode *head){ if(head->next==NULL || head==NULL) return head; ListNode *current=head->next; ListNode *temp=NULL; while(current!=NULL){ temp=head; while(temp->val < current->val && temp != current){ temp=temp->next; } if(temp!=current){ int first=current->val; int second; while(temp!=current){ second=temp->val; temp->val=first; first=second; temp=temp->next; } temp->val=first; } current=current->next; } return head; } int main(){ int n,a; cin>>n; ListNode *head,*p,*q; head = (ListNode *)malloc(sizeof(ListNode)); q=head; for(int i=0;i<n;i++){ cin>>a; p=(ListNode *)malloc(sizeof(ListNode)); p->val=a; q->next=p; q=p; } q->next=NULL; head=head->next; ListNode *res=insertionSortList(head); while(res!=NULL){ cout<<res->val<<" "; res=res->next; } cout<<endl; return 0; }
相关文章推荐
- Leetcode: Insertion Sort List
- 【LEETCODE】147- Insertion Sort List [Python]
- Leetcode Insertion Sort List
- LeetCode: Insertion Sort List
- LeetCode147 Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode - Insertion Sort List
- Leetcode 147 Insertion Sort List
- [leetcode] Insertion Sort List
- leetcode 147: Insertion Sort List
- LeetCode 之 Insertion Sort List — C++ 实现
- leetcode - Insertion Sort List
- LeetCode----Insertion Sort List
- LeetCode | Insertion Sort List
- leetCode(4):Insertion Sort List
- LeetCode-M-Insertion Sort List
- Leetcode: Insertion Sort List
- [leetcode] Insertion Sort List
- LeetCode 147 Insertion Sort List
- Insertion Sort List —— LeetCode