首页 > 代码库 > Leetcode Insertion Sort List
Leetcode Insertion Sort List
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);}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。