标签:style class blog code ext color
Sort a linked list using insertion sort.
单链表的插入排序, 考查的时单链表指针的断开和插入操作
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x):val(x), next(NULL){} }; void printList(ListNode* head){ while(head!=NULL){ cout<<"->"<<head->val; head = head->next; } cout<<endl; } ListNode *insertionSortList(ListNode *head){ if(head == NULL || head->next == NULL) return head; ListNode *newHead = new ListNode(-1); newHead->next = head; ListNode *pre = head,*p = head->next; while(p!=NULL){ ListNode *q = newHead; while(q->next!=p){ if(q->next->val >= p->val ){ pre->next = p->next; p->next = q->next; q->next = p; p=pre->next; break; }else{ q = q->next; } } if(q->next == p) { pre = p; p = p->next; } } ListNode *res = newHead->next; delete newHead; return res; } int main(){ ListNode* head = new ListNode(3); ListNode* node1 = new ListNode(2); ListNode* node2 = new ListNode(4); head->next = node1; node1->next = node2; ListNode *a = insertionSortList(head); cout<<"ans:"<<endl; printList(a); }
Leetcode Insertion Sort List,布布扣,bubuko.com
标签:style class blog code ext color
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3794939.html