双向链表加数
来源:互联网 发布:无锡网络开发有限公司 编辑:程序博客网 时间:2024/05/22 23:18
ps:可能有错,请大佬指出。不考虑插头和插尾的情况。
附丑图一张
#include <iostream>
#include <string.h>#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
struct node *pre;//前指针
struct node *next;//后指针
};
int main()
{
struct node *p,*t,*head,*q,*flag;
int n,a;
while(cin>>n)//输入N个数
{
head=NULL;//地址为空
for(int i=1;i<=n;i++)
{
cin>>a;//输入一个数字
p=(struct node *)malloc(sizeof(struct node));//开辟一个新空间
p->data=a;//把输入的数存起来
p->next=NULL;//存在的意义:当输入完最后一个数字后,他的后指针为空
p->pre=NULL;//同理,输入第一个数字时,他的前指针为空
if(head==NULL)
head=p;
else
{
p->pre=q;//新开辟的空间的前指针指向上一个地址
q->next=p;//上一个地址的后指针指向新开辟的空间
}
q=p;
}
int local,test=0;
cin>>local>>a;//输入想要插入的位置,和数
p=(struct node*)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
p->pre=NULL;
t=head;
while(t!=NULL)//从头开始遍历
{
test++;
if(test==local-1)
{
p->next=t->next;//把新开辟空间的后指针指向你想要插入位置的地址
t->next->pre=p;//将你想要插入的位置的前指针指向新开辟的空间
t->next=p;//将你想要插入的前一个位置的后指针指向现在开辟的空间
p->pre=t;//将新开辟空间的前指针指向插入的前一个位置;
break;
}
t=t->next;
}
t=head;//从头开始遍历
while(t!=NULL)
{
cout<<t->data<<" ";
if(t->next==NULL)//到最后一个数字时,用falg记录地址
flag=t;
t=t->next;
}
cout<<endl;
t=flag;//从尾开始遍历
while(t!=NULL)
{
cout<<t->data<<" ";
t=t->pre;
}
cout<<endl;
}
return 0;
}
0 0
- 双向链表加数
- 单向链表,加数
- SzNOI 双向约瑟夫(双向链表)
- 双向链表&&堆栈
- 双向链表
- 使用双向链表
- 双向链表
- 双向循环链表
- 双向循环链表
- 双向链表
- 实现双向链表
- 双向循环链表
- 建立双向链表
- 双向链表
- 双向链表
- 双向循环链表
- 双向链表
- 链表-双向链表
- 关于 自守数 的C语言算法
- python正则表达式
- 【Android】【Webview】WebView 简介
- 第二讲:index渲染指令.html
- 基于java类库的3DES加密算法实现
- 双向链表加数
- CentOS 6上使用C++调用Redis
- 【Unity&NGUI】为什么把NGUI的UI制作为预制体,再生成到新场景,UI无法正常在Game视图显示
- 关于ZJOI2017day2的感想 #1
- boot-factory模式
- 安卓漫漫路之BitmapFactory高效加载Bitmap.
- ios 类别和类扩展
- WIFI 模块上传服务器显示曲线
- uva10791 唯一分解定理