数据结构之双线链表

双向链表的相关操作


// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

typedef struct Node
{
	int x;
	Node *next;
	Node *pre;
}Node,*Lnode;

void creat(Node& node,int n,int *a)
{
	Lnode p=&node,q;
	for(int i=n-1;i>=0;i--)
	{
		q= new Node;
		q->next=NULL;
		q->pre=NULL;
		q->x=a[i];

		p->next->pre=q;
		q->next=p->next;
		q->pre=p;
		p->next=q;
	}
}

bool Del(Node& node,int num)
{
	Lnode p=node.next,q=&node;
	for(p;p!=q;p=p->next)
	{
		if(p->x==num)   //  找到这个元素num了
		{
			q=p;
			p->pre->next=p->next;
			p->next->pre=p->pre;
			free(q);
			return true;
		}
	}
	return false;
}
void Prin(Node& node)
{
	Lnode p=node.next,q=&node;
	for(p;p!=q;p=p->next)
		cout<<p->x<<endl;
	cout<<"end"<<endl;
}
bool Add(Node& node,int i,int num)
{   //  在第i个位置插入元素num(默认从head开始)
	Lnode p=node.next,q=&node;
	int k=1;
	for(;k<i;p=p->next,k++)  ;
	//   现在就相当于在q和p中插入一个元素
	Lnode r=new Node;
	r->x=num;
	r->next=r->pre=NULL;

	p->pre->next=r;
	r->pre=p->pre;

	r->next=p;
	p->pre=r;
	return true;
}
void SupPrin(Node& node ,int i)   //  为了验证循环列表的正确性,从第i个节点开始输出
{
	Lnode p=node.next,q;
	int k=1;
	for(;k<i;) 
	{
		p=p->next;
		k++;
	}
	//  现在是从p开始打印了
	//  需要注意到一点是,我这个node类型,head是空的,在输出结果的时候需要跳过head.x

	q=p;
	for(p;p!=&node;p=p->next)
		cout<<p->x<<endl;
	
	p=node.next;
	for(;p!=q;p=p->next)
		cout<<p->x<<endl;
	cout<<endl;

}
int main()
{
	Node head;
	head.next=&head;
	head.pre=&head;
	int a[5]={2,3,5,1,78};
	creat(head,5,a);
	Prin(head);
	bool t1=Del(head,5);
	cout<<t1<<endl;
	Prin(head);
	cout<<endl<<endl;
	SupPrin(head,2);
	cout<<endl<<endl;
	Add(head,2,45);
	Add(head,2,35);
	Add(head,2,15);
	Add(head,2,65);
	Prin(head);
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值