数据结构 P30 算法实现 链表的头插法 尾插法
2017-09-30 16:05
399 查看
/*链表的正向建立—头插法 & 链表的逆向建立—尾插法 算法2.11*/
#include<iostream>
#define OK 1
#define ERROR 0
int a,b;
using namespace std;
struct node
{
int date;
node *next;
};
class List
{
node *head;
public:
List() {head=NULL;}
int choice(int a);
void inser_infront(int b); //头插
void inser_inend(int b); //尾插
void output();
};
int List::choice(int a)
4000
{
if (a==0)
inser_infront(b);
else if(a==1)
inser_inend(b);
else if(a==2)
{
if(head==NULL)
cout<<"抱歉,暂时链表里面无可打印数据!!!"<<endl;
else
output();
}
else
return ERROR;
}
void List:: inser_infront(int b)
{
node *p,*s; //p指向链表节点的指针 s新增的节点
cout<<"请输入要插入的数据:";
cin>>b;
p=head;
s=new node();
s->date=b;
s->next=NULL;
if(head==NULL)
head=s;
else
{
s->next=p;
head=s;
}
}
void List:: inser_inend(int b)
{
cout<<"请输入要插入的数据:";
node *p,*s;
cin>>b;
s=new node();
s->date=b;
s->next=NULL;
if (head==NULL)
head=s;
else
{
p=head;
while (p->next!=NULL)
{p=p->next;}
p->next=s;
}
}
void List::output()
{
node *p;
p=head;
cout<<"现在的链表为:";
while (p->next!=NULL)
{
cout<<p->date<<",";
p=p->next;
}
cout<<p->date<<endl;;
}
int main()
{
List L;
while (1)
{
cout<<"0:在链表前端插入数据"<<endl<<"1:在链表尾端插入数据"<<endl<<"2:打印链表"<<endl;
cout<<"你的选择是:";
cin>>a;
L.choice(a);
}
return 0;
}
#include<iostream>
#define OK 1
#define ERROR 0
int a,b;
using namespace std;
struct node
{
int date;
node *next;
};
class List
{
node *head;
public:
List() {head=NULL;}
int choice(int a);
void inser_infront(int b); //头插
void inser_inend(int b); //尾插
void output();
};
int List::choice(int a)
4000
{
if (a==0)
inser_infront(b);
else if(a==1)
inser_inend(b);
else if(a==2)
{
if(head==NULL)
cout<<"抱歉,暂时链表里面无可打印数据!!!"<<endl;
else
output();
}
else
return ERROR;
}
void List:: inser_infront(int b)
{
node *p,*s; //p指向链表节点的指针 s新增的节点
cout<<"请输入要插入的数据:";
cin>>b;
p=head;
s=new node();
s->date=b;
s->next=NULL;
if(head==NULL)
head=s;
else
{
s->next=p;
head=s;
}
}
void List:: inser_inend(int b)
{
cout<<"请输入要插入的数据:";
node *p,*s;
cin>>b;
s=new node();
s->date=b;
s->next=NULL;
if (head==NULL)
head=s;
else
{
p=head;
while (p->next!=NULL)
{p=p->next;}
p->next=s;
}
}
void List::output()
{
node *p;
p=head;
cout<<"现在的链表为:";
while (p->next!=NULL)
{
cout<<p->date<<",";
p=p->next;
}
cout<<p->date<<endl;;
}
int main()
{
List L;
while (1)
{
cout<<"0:在链表前端插入数据"<<endl<<"1:在链表尾端插入数据"<<endl<<"2:打印链表"<<endl;
cout<<"你的选择是:";
cin>>a;
L.choice(a);
}
return 0;
}
相关文章推荐
- 数据结构与算法:单向链表实现与封装(有头)
- C++类模板 实现双向循环链表的基本算法 《数据结构》(C++版 北京科海)中摘抄
- 算法与数据结构 其二 数组和链表 的实现
- 数据结构 P36-37 算法实现 双向循环链表的插入与删除
- 用链表实现“啦啦啦”等算法或数据结构(持续更新)
- 算法与数据结构-单向链表的基本操作C语言实现
- Android版数据结构与算法(三):基于链表的实现LinkedList源码彻底分析
- 数据结构 P31 算法实现 有序链表合并为有序链表
- 【数据结构和算法分析】单链表的基本实现
- 算法与数据结构基础系列(一): 链表的常见问题分析及实现
- 经典算法与数据结构的c++实现——带头结点的单链表
- 数据结构与算法:单链表(利用万能指针实现对任意类型数据进行操作)
- [数据结构]java实现的简单链表的 头/尾插法
- 算法与数据结构【二】简单链表的实现
- 算法与数据结构课程中的c++实现的顺序表和链表
- 严蔚敏版数据结构课本代码——链表结构实现算法2.2(BUCT-JK1602-LLP)
- 数据结构 P38 算法实现 在带头结点的单链表的第i个元素插入元素e
- C++数据结构--单向循环链表(实现头插法,尾插法)
- 算法与数据结构-链表 讲解与java代码实现
- 头疼的算法与数据结构——链表实现栈