(数据结构)(C++)双链表的建立和部分基本操作

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
 
using namespace std;
 
#define  ElemType int

#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
 
typedef struct DLnode{
	ElemType data;
	struct DLnode* next;
	struct DLnode* prior; 
}DLnode,*DLinkList;

//头插法
void CreateListH(DLinkList &L){
	DLinkList s;
	L=new DLnode;
	L->prior=L->next=NULL;
	cout<<"请输入你要插入元素个数:";
	int num;
	cin>>num;
	int i;
	for(i=0;i<num;i++){
	  s=new DLnode;
	  cout<<"请输入第"<<i+1<<"个元素值:";
	  ElemType elem; 
	  cin>>elem;
	  s->data=elem;
	  s->next=L->next;
	  if(L->next!=NULL){
	  	L->next->prior=s;
	  }
	  L->next=s;
	  s->prior=L;
	} 
} 

//尾插法 
void CreateListT(DLinkList &L){
	DLinkList s,r;
	L=new DLnode;
	r=L;
	cout<<"请输入你要插入元素个数:";
	int num;
	cin>>num;
	int i;
	for(i=0;i<num;i++){
		s=new DLnode;
		cout<<"请输入第"<<i+1<<"个元素:";
		ElemType elem; 
		cin>>elem; 
		s->data=elem;
		r->next=s;
		s->prior=r;
		r=s;
	} 
	r->next=NULL;
}

//打印链表
void PrintList(DLinkList L){
	DLinkList p;
	p=L->next;
	while(p!=NULL){
		cout<<p->data<<"\t";
		p=p->next; 
	} 
	cout<<endl;
} 

//插入 
bool InsertList(DLinkList &L,int i){
	//i为插入位置物理位置 
	cout<<"请输入你要插入的元素";
	ElemType elem;
	cin>>elem; 
	int j=0;
	DLinkList p,s;
	p=L;
	if(i<=0){
		return false;
	}
	while(j<i-1&&p!=NULL){
		j++;
		p=p->next;
	} 
	if(p==NULL){//未找到第i-1个结点 
		return false;
	}else{
		s=new DLnode;
		s->data=elem;
		s->next=p->next;
		if(p->next!=NULL){
			p->next->prior=s; 
		} 
		s->prior=p;
		p->next=s;
		return true;
	} 
} 


int main(){
	DLinkList L;
	CreateListH(L);
	cout<<"此表为尾插表L"<<endl; 
	PrintList(L);
    cout<<endl;
    
    DLinkList L1;
	CreateListT(L1);
	cout<<"此表为头插法L1"<<endl;
	PrintList(L1); 
	cout<<endl;
	

	
	cout<<"请输入你要插入的双链表L1的位置:";
	int location; 
	cin>>location;
	InsertList(L1,location);
	PrintList(L1); 
	
	
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值