主题:循环链表移动
我最近写了一个循环移动的算法,可是总是出错,求高手相助找下错。我觉得可能是展示函数出错了吧。。。。。
#include<iostream>
using namespace std;
typedef struct Clist
{
char data;
struct Clist *next;
}*Link;
Link Creat(Link &S)//初始化一个循环链表,并给把第一个字符放入头节点
{
S=(Link)malloc(sizeof(Clist));
cout<<"Please input the first data"<<endl;
cin>>S->data;
S->next=S;
return S;
}
void input(Link &S,int n)//输入剩下的n-1个字符
{
Link p,s;
s=Creat(S);
int i;
cout<<"Please input the other data of you key"<<endl;
for(i=n-1;i>0;i--)
{
p=(Link)malloc(sizeof(Clist));
cin>>p->data;
p->next=s->next;
s->next=p;
s=p;
}
}
void display(Link &S)
{
Link p;
p=S;
while(p!=S)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
bool Move(Link &S,int n)//循环链表移动。
{
Link p,h,r,q;
p=S;
h=p;
while(n!=0)
{
q=p->next;
r=(Link)malloc(sizeof(Clist));
while(q->next!=h)
{
p=p->next;
q=q->next;
}
r->data=q->data;
r->next=q->next;
p->next=r;
p=r;
h=p;
free(q);
n--;
}
display(p);
return true;
}
void main()
{
Link S;
int num1,num2;
cout<<"Please input the num of your key"<<endl;
cin>>num1;
input(S,num1);
cout<<"Please input the mima"<<endl;
cin>>num2;
Move(S,num2);
if(Move(S,num2))
cout<<"You have set successfully"<<endl;
else
cout<<"please try again"<<endl;
}
#include<iostream>
using namespace std;
typedef struct Clist
{
char data;
struct Clist *next;
}*Link;
Link Creat(Link &S)//初始化一个循环链表,并给把第一个字符放入头节点
{
S=(Link)malloc(sizeof(Clist));
cout<<"Please input the first data"<<endl;
cin>>S->data;
S->next=S;
return S;
}
void input(Link &S,int n)//输入剩下的n-1个字符
{
Link p,s;
s=Creat(S);
int i;
cout<<"Please input the other data of you key"<<endl;
for(i=n-1;i>0;i--)
{
p=(Link)malloc(sizeof(Clist));
cin>>p->data;
p->next=s->next;
s->next=p;
s=p;
}
}
void display(Link &S)
{
Link p;
p=S;
while(p!=S)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
bool Move(Link &S,int n)//循环链表移动。
{
Link p,h,r,q;
p=S;
h=p;
while(n!=0)
{
q=p->next;
r=(Link)malloc(sizeof(Clist));
while(q->next!=h)
{
p=p->next;
q=q->next;
}
r->data=q->data;
r->next=q->next;
p->next=r;
p=r;
h=p;
free(q);
n--;
}
display(p);
return true;
}
void main()
{
Link S;
int num1,num2;
cout<<"Please input the num of your key"<<endl;
cin>>num1;
input(S,num1);
cout<<"Please input the mima"<<endl;
cin>>num2;
Move(S,num2);
if(Move(S,num2))
cout<<"You have set successfully"<<endl;
else
cout<<"please try again"<<endl;
}