栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

备忘录:交换双向链表元素

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

备忘录:交换双向链表元素

#include
#include
#include
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948547.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号