[leetcode] Insertion Sort List
来源:互联网 发布:apache 负载压力测试 编辑:程序博客网 时间:2024/06/08 01:25
Sort a linked list using insertion sort.
思路:设立两个指针,当前指针和插入位置指针,当发现当前指针比插入位置值要小时,将两者的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;}
0 0
- Insertion Sort List | leetcode
- 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
- LeetCode - Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List (LeetCode)
- [LeetCode] Insertion Sort List
- [LeetCode]Insertion Sort List
- leetcode Insertion Sort List
- Insertion Sort List -- LeetCode
- Insertion Sort List (LeetCode)
- LeetCode Insertion Sort List
- leetcode Insertion Sort List
- 砭石让你在秋天提高免疫力。砭石砭石厂家
- Bitcoin Core APIs
- Django 数据库访问优化
- Codeforces Round #254 (Div. 2) A. DZY Loves Chessboard
- Ubuntu 查看内存命令
- [leetcode] Insertion Sort List
- Java——jdk1.5新特性
- 线段树。模板
- Netty In Action 读书笔记 - 第七章 Codec
- OpenEIM 码农的“启蒙”之《面向对象分析和设计》
- 可重入函数和线程安全函数
- Java虚拟机工作原理详解
- BitCoin Tutorial
- Kerberos初体验--安装。