当前位置: 首页 > news >正文

双向链表的基本操作

#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
typedef long long ll;
typedef struct line
{int data;struct line *pre;//前指针struct line *next;//后指针
}line,*a;
line* init_line(line*head)
{cout<<"请输入双向链表的大小:";int size;cin>>size;if(size<1) return NULL;//申请空间与初始化head=(line*)malloc(sizeof(line));head->pre=NULL;head->next=NULL;cout<<"请输入头结点的数值大小:";int data;cin>>data;head->data=data;//赋值完头节点之后开始后续的节点的创建int pos=1;line *ls=head;while(pos<=size){line *node=(line*)malloc(sizeof(line));node->pre=NULL;node->next=NULL;cout<<"请输入第"<<pos<<"结点的数值大小:";pos++;cin>>data;node->data=data;ls->next=node;node->pre=ls;ls=ls->next;}return head;
}
line *ls_insert(line*head,int pos,int data)
{//先初始化要添加的node//指针一定要置空line *node=(line*)malloc(sizeof(line));node->data=data;node->pre=NULL;node->next=NULL;//插入链表的表头if(pos==1){node->next=head;head->pre=node;head=node;//此时head指针指向第一个位置}else{line *p=head;//指向插入位置的前一个位置for(int i=1;i<pos-1;i++){p=p->next;}//如果此时指针不为空就代表不是最后一个if(p->next){//需要有序替换四条线p->next->pre=node;node->next=p->next;p->next=node;node->pre=p;}//如果插入位置是表尾else{//相互连接就行p->next=node;node->pre=p;}}return head;
}
line *ls_delete(line *head,int data)
{//只要引用头节点指针即可line* ls=head;while(ls){//遍历判断即可if(ls->data==data){ls->pre->next=ls->next;ls->next->pre=ls->pre;free(ls);cout<<"已经成功删除!"<<endl;return head;}//没搜到就往下遍历即可ls=ls->next;}
}
void ls_display(line *head)
{line *ls=head;int pos=1;while(ls){cout<<"第"<<pos<<"个数据是:"<<ls->data<<endl;pos++;ls=ls->next;}
}
int main()
{cout<<"**************************************"<<endl;cout<<"创建双链表操作"<<endl;line *head=NULL;head=init_line(head);ls_display(head);cout<<"**************************************"<<endl;cout<<"插入双链表操作"<<endl;head=ls_insert(head,2,40);ls_display(head);cout<<"**************************************"<<endl;cout<<"删除双链表操作"<<endl;head=ls_delete(head,40);ls_display(head);cout<<"**************************************"<<endl;cout<<"所有操作结束"<<endl;cout<<"**************************************"<<endl;return 0;
}

http://www.lryc.cn/news/412410.html

相关文章:

  • modbus tcp和modbusRTU的区别是什么?
  • web小游戏开发:拼图(四)对调和移动拼图玩法的实现
  • 前端:Vue学习 - 智慧商城项目
  • KVM调整虚拟机与CPU铆钉(绑定)关系
  • 华火电焰灶:烹饪新宠,温暖与美味的完美融合
  • 理想发周榜,不是新能源市场的原罪
  • AHK是让任何软件都支持 Shift + 鼠标滚轮 实现界面水平滚动
  • 如何在C语言中实现求解超级丑数
  • secExample靶场之java反序列化漏洞复现
  • 解决升级Linux内核后,open files设置无效的问题。
  • 关于防范勒索病毒Play新变种的风险提示
  • 一款.NET开源、跨平台的DASH/HLS/MSS下载工具
  • MATLAB学习日志DAY21
  • Spingboot请求tcp 方式
  • leetcode刷题日记-括号生成
  • 小程序按钮分享
  • 多模态多智能体,在实现系统2(深思熟虑)方面的探索
  • 【CAN通讯系列8】如何准确接收数据?
  • RabbitMQ知识总结(基本概念)
  • Prel语言入门学习:一篇全面的指南
  • 在云服务器上自动化部署项目,jenkins和gitee
  • python 参数输入
  • Spring面试篇章——Spring基本概述
  • 股票预测模型中注意力多层Attention RNN LSTM 的应用
  • C语言 | Leetcode C语言题解之第313题超级丑数
  • PHP健身微信小程序系统源码
  • 树组件 el-tree 数据回显
  • 54、PHP 实现希尔排序
  • linux 虚拟机解压arm-linux-gcc-4.6.4-arm-x86_64.tar.bz2并arm-linux-gcc
  • 泛化的最近点迭代法(Generalized-ICP)