上代码
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
typedef struct node
{
int date;
struct node *next;
struct node *prior;
}node;
class Link
{
private:
node *first;
node *last;
node *temp;
int len;
public:
void addLink();
void showLink();
void Swap(node *,node *);
void sort();
int getLen() const {
return len;
}
void setLen(int len) {
this->len = len;
}
};
void Link::addLink()
{
srand((unsigned)time(NULL));
for(int i=1;i<=len;i++)
{
if(i==1)
{
node *newnode=new node;
newnode->date=rand()%101;
first=newnode;
temp=newnode;
first->prior=NULL;
}else if(i==len){
node *newnode=new node;
newnode->date=rand()%101;
last=newnode;
temp->next=last;
last->prior=temp;
temp=newnode;
temp->next=NULL;
}else
{
node *newnode=new node;
newnode->date=rand()%101;
temp->next=newnode;
newnode->prior=temp;
temp=newnode;
}
}
}
void Link::showLink()
{
node *temp=new node;
temp=first;
while(temp!=NULL)
{
cout<<temp->date<<" ";
temp=temp->next;
}
cout<<endl;
temp=last;
/*while(temp!=NULL)
{
cout<<temp->date<<" ";
temp=temp->prior;
}*/
}
上面的是双向链表的建立和打印,代码没错
下面的是选择排序算法,应该也没错
void Link::sort()
{
node *i,*j,*k;
//if(!first->next)
//return;
for(i=first;i->next!=NULL;i=k->next)
{
for(j=i->next,k=i;j!=NULL;j=j->next)
if(k->date>j->date)
k=j;
if(k!=i)
Swap(i,k);
}
下面的是交换链表位置的代码,复制的某位大神(原谅我忘记了他的名字)的代码,由于他的代码中没有对头结点的换位方法,我就自己写了加上去,结果每次运行都会丢失比头结点小的数据
void Link::Swap(node *p,node *t)
{
node *temp;
if(t->next==NULL&&p->prior!=NULL) //t结点是否为尾结点
{
if(p->next==t) //p,t结点是否相邻
{
//与尾结点相邻的交换代
t->next=p;
t->prior=p->prior;
p->next=NULL;
p->prior->next=t;
p->prior=t;
}
else
{
//与尾结点不相邻的交换代
t->next=p->next;
t->prior->next=p;
temp=t->prior;
t->prior=p->prior;
p->next->prior=t;
p->next=NULL;
p->prior->next=t;
p->prior=temp;
}
}
else if(p->prior==NULL&&t->next!=NULL)
{
if(p->next==t)
{
p->next=t->next;
p->next->prior=p;
p->prior=t;
t->next=p;
t->prior=NULL;
}
else
{
temp=p->next;
p->next=t->next;
t->next->prior=p;
p->prior=t->prior;
t->prior->next=p;
t->next=temp;
temp->prior=t;
t->prior=NULL;
}
}
else if(p->prior==NULL&&t->next==NULL)
{
p->next->prior=t;
t->next=p->next;
p->next=NULL;
t->prior->next=p;
p->prior=t->prior;
t->prior=NULL;
}
else{
if(p->next==t) //p,t结点是否相邻
{
//相邻的交换代
t->next->prior=p;
temp=t->next;
t->next=p;
t->prior=p->prior;
p->next=temp;
p->prior->next=t;
p->prior=t;
}
else
{
//不相邻的交换代
t->next->prior=p;
temp=t->next;
t->next=p->next;
p->next->prior=t;
p->next=temp;
t->prior->next=p;
temp=t->prior;
t->prior=p->prior;
p->prior->next=t;
p->prior=temp;
}
}
}
大神们来帮个忙吧,找错误找的眼睛都出血丝了。。。