双链表

#include<bits/stdc++.h>

using namespace std;

typedef struct DNode{
	struct DNode *prior, *next;//不可写成struct DNode *prior, next; *要和变量一起 
	int data; 
}*DLinklist,DNode;

void Print(DLinklist L){
	DNode* r = L; 
	while(r->next !=NULL){
		r = r->next;
		cout << r->data << " ";
	}
	cout << endl;
	while(r != L){
		cout << r->data << " ";
		r = r->prior; 
	} 
	cout << endl;
}
bool Create(DLinklist& L){
	L = (DNode*)malloc(sizeof(DNode));
	if (!L) false;
	L->prior = L->next = NULL;
	DNode* r = L; 
	int c;
	cin >> c ;
	while(c != -1){
		DNode* p = (DNode*)malloc(sizeof(DNode));
		p->data = c;
		p->prior = r;
		r->next = p;
		r = p;
		cin >> c ;
	}
	r->next = NULL;
	return true;
} 

DNode* GetElem(DLinklist L, int side){
	int i = 0;//把头结点看作0号结点 
	DNode* r = L;
	while(r->next != NULL && i < side){
		r = r->next;
		i++;
	}
	if (i == side) return r;
	else return NULL; 
} 



bool Insert(DLinklist& L, int side, int data){
	DNode *r = GetElem(L, side-1);
	DNode *p = (DNode*)malloc(sizeof(DNode));
	if(p&&r){
		p->data = data;
		p->next = r->next;
		if(r->next){
			r->next->prior = p;	
		}
		r->next = p;
		p->prior = r; 
		return true;
	}
	else return false;	
} 


bool Delete(DLinklist& L, int side){
	DNode *r = GetElem(L, side);
	if(r){
		r->prior->next = r->next;
		if(r->next) r->next->prior = r->prior;
		free(r);
		return true;
	}
	else return false;	
} 

int main(){
	DLinklist L;
	Create(L);
	Print(L);
	Insert(L, 0, 999);
	Print(L);
	Delete(L,4); 
	Print(L);
	
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值