//前驱从小到大4-3-2-1;
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100005],n;
bool cmp(int x,int y){
return x>y;
}
typedef struct Lnode{
int data;
struct Lnode *next,*prior;
bool flag;
}Lnode,*LinkList;
enum Status{
OK=1,
ERROR=0
};
Status InitList(LinkList L,int n){
//根据输入初始化一个单向的链式表
LinkList r,l;
L->data=a[1];
L->next=NULL;
l=L;
for(int i=2;i<=n;i++){
r=new Lnode;
r->data=a[i];
r->next=NULL;
l->next=r;
l=r;
}
return OK;
}
Status solve(LinkList &L,int n,int m){
cout<<"n="<<n<<" m="<<m<<endl;
LinkList p,q;
p=L;
q=L;
while(p){
//先找到需要加前驱的数据位置
// cout<<"p->data "<<p->data<<endl;
if(p->data==n&&p->flag!=1){
while(q){
//找到需要连接的前驱
// cout<<"q->data "<<q->data<<endl;
if((q->data==m)&&q!=p){
cout<<"yes"<<endl;
p->prior=q;
p->flag=1;
break;
}
q=q->next;
}
break;
}
p=p->next;
}
return OK;
}
int main()
{
LinkList head,phead;
printf("please enter a number ");
scanf("%d",&n);
printf("enter %d number \n",n);
for(int i=1;i<=n;i++){
cin>>a[i];
}
head=new Lnode;
InitList(head,n);
sort(a+1,a+n+1,cmp);
for(int i=1;i<n;i++){
// cout<<"i="<<i<<endl;
solve(head,a[i],a[i+1]);
}
phead=head;
while(phead){
if(phead->data==a[n]&&phead->flag!=1){
phead->prior=NULL;
}
phead=phead->next;
}
printf("预期的前驱顺序:\n");
for(int i=1;i<=n;i++){
cout<<a[i]<<" \n"[i==n];
}
phead=head;
printf("按照存储顺序输出\n");
while(phead){
printf("%d ",phead->data);
phead=phead->next;
}
phead=head;
LinkList mhead;
while(phead){
if(phead->data==a[1]){
mhead=phead;
break;
}
phead=phead->next;
}
printf("\n");
printf("按照前驱顺序输出\n");
while(mhead){
printf("%d ",mhead->data);
mhead=mhead->prior;
}
}
双向链式表
于 2022-03-17 17:06:13 首次发布