#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct dnode
{
int data;
struct dnode *prior,*next;
}dnode,*DLIST;
//初始化双向链表
void initiadlist(DLIST &l)
{
l=(dnode *)malloc(sizeof(dnode));
l->next=l->prior=NULL;
printf("初始化链表成功!\n");
}
//随机建立链表
void crealist(DLIST &l)
{
dnode *s;
s=(dnode *)malloc(sizeof(dnode));
s=l;
int i=1;
while (i<=10)
{
dnode *t;
t=(dnode *)malloc(sizeof(dnode));
t->data=rand()%50+3;
s->next=t;
t->prior=s;
s=t;
i++;
}
s->next=NULL;
}
//查找元素的位置
int findelist(DLIST l,int x)
{
int i=1;
dnode *s;
s=l->next;
while (s)
{
if(s->data==x)
return i;
i++;
s=s->next;
}
return -1;
}
//交换元素x和它的前驱结点元素
int swap(int x,DLIST &l)
{
int i,j;
dnode *s;
s=l;
j=findelist(l,x);
i=1;
if(j==1)
{
printf("当前元素在第一个位置,无需要交换!\n");
return 0;
}
else if(j!=-1)
{
while (i<=j)
{
s=s->next;
i++;
}
int temp;
temp=s->data;
s->data=s->prior->data;
s->prior->data=temp;
}
else
{
printf("\n未查找到%d元素,不进行交换\n",x);
return 0;
}
}
//输出链表
void putlist(DLIST l)
{
l=l->next;
while (l)
{
printf("%d ",l->data);
l=l->next;
}
}
int main()
{
DLIST l;
int x,f;
initiadlist(l);
crealist(l);
putlist(l);
printf("请输入元素值x:\n");
scanf("%d",&x);
f=swap(x,l);
if (f!=0)
{
printf("交换成功,链表内容为:\n");
putlist(l);
}
else
{
printf("交换失败,链表内容为:\n");
putlist(l);
}
return 0;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交