演算法的思想,將要排序的鏈表分成兩部分A和B,A中初始放入鏈表中的第一個元素,B為鏈表中的剩餘元素。將B中的元素一次插入A中,並排好順序,直到B中元素為空白。
代碼奉上= =、
#include <iostream>
using namespace std;
struct Node{
int element;
Node *next;
};
Node *h = NULL;
struct ANode{
int element;
ANode *next;
};
ANode *head = NULL;
bool insert(int a,Node *&h){
int click = 0;
Node *p ;
p = new Node;
p->element = a;
if (h ==NULL)
{
h = p;
p->next = NULL;
click = 1;
}else{
Node *qn ;
qn = h;
while (qn->next!=NULL)
{
qn = qn->next;
}
qn->next = p;
p->next = NULL;
click = 1;
}
if (click ==0)
{
return false;
}else
return true;
}
ANode *sort(Node *&h){
Node *q = h;
ANode *p;
p = new ANode;
p->element = q->element;
head = p;
h = h->next;
p->next = NULL;
delete q;
while (h!=NULL)
{
Node *q = h;
ANode *p,*p1 = head,*p2 = head;
p = new ANode;
p->element = q->element;
while ((p->element>p1->element)&&(p1->next!=NULL))
{
p2 = p1;
p1 = p1->next;
}
if (p->element<p1->element)
{
if (p1==head)
{
head = p;
p->next = p1;
h = h->next;
delete q;
}else{
p2->next = p;
p->next = p1;
h = h->next;
delete q;
}
}
else if (p->element ==p1->element)
{
if (p1==head)
{
head = p;
p->next = p1;
h = h->next;
delete q;
}else{
p2->next = p;
p->next = p1;
h = h->next;
delete q;
}
}
else if (p1->next ==NULL)
{
p1->next = p;
p->next = NULL;
h = h->next;
delete q;
}
}
return head;
}
void main(){
int a;
bool t;
int i=0;
while(true)
{
char ch;
cout<<"請輸入要插入的數值:";
cin>>a;
t=insert(a,h);
if(t)
cout<<"插入成功"<<endl;
else
cout<<"插入失敗"<<endl;
cout<<"要繼續插入嗎?(y/n)";
cin>>ch;
if(ch=='N'||ch=='n')
break;//break的作用是退出包含它的最內層迴圈
}
Node *q=h;
cout<<"鏈表的元素依次為:"<<endl;
while(q->next!=NULL)
{
cout<<q->element<<' ';
q=q->next;
}
cout<<q->element<<endl;
head=sort(h);
ANode *q1=head;
cout<<"排序後的鏈表元素依次為:"<<endl;
while(q1->next!=NULL)
{
cout<<q1->element<<' ';
q1=q1->next;
}
cout<<q1->element<<endl;
}
感覺這個代碼主要是要理清楚演算法。
然後想到了程式=資料結構+演算法這句話的真諦、
晚安晚安,碎告碎告咯