算法不会,尚能饭否之排序——插入排序法(用链表实现)

      看算法看到了插入法排序,现在就把小弟用链表实现的插入法排序贴上来吧,希望大家提出意见,谢谢!如果各位大虾有更好的写法,可以和我讨论,如果我写的不好,也可以给我提出来,本人用的是vs2008。/*************************************************************************** *FileName:InsertSortLinked.cpp * *Author:FlySky Young * *Data:Nov/16/2010 * *Description:Because the fight with my girlfriend, * *so write a program to make myself calm down. * ****************************************************************************/ #include <iostream> using namespace std; class Node { public: int value; Node *next; }; //插入排序,建立链表 void insert(Node *&head, int data) { Node *s = NULL; Node *p = NULL; Node *q = NULL; s = new Node(); s->value = data; s->next = NULL; //如果头指针是空的,就将head指向s if (head == NULL) { head = s; return; } //如果值比头小,就插入头结点之前 if (head->value > s->value) { s->next = head; head = s; return; } //搜索插入 for (q = head, p = head->next; p; q = p, p = p->next) { if (p->value > s->value) { s->next = p; q->next = s; return; } } q->next = s; return; } void showList(Node *head) { while (head) { cout<<head->value<<" "; head = head->next; } return; } void main() { int k; Node *head = NULL; cin>>k; //输入值 while (k != -1) { insert(head, k); cin>>k; } showList(head); //输出有序链表 }

你可能感兴趣的:(算法不会,尚能饭否之排序——插入排序法(用链表实现))