当前位置:   article > 正文

C++数据结构--双向链表_c++ 双向链表

c++ 双向链表

测试代码

#include <iostream>
#include <iomanip>
using namespace std;
template <class DataType>
struct DulNode
{
	DataType data;
	DulNode <DataType>*prior,*next;
};
template <class DataType>
class DoubleList
{
public:
  DoubleList(DataType a[],int n);//建立双向链表
  void Insert(int i,DataType x);//插入操作,在第i个位置插入元素x
	DataType Delete (int i);//删除第i个元素
	void PrintList();//遍历操作,按序号依次输出元素
  
private:
  DulNode<DataType> *first;
};
template <class DataType>
DoubleList<DataType>::DoubleList(DataType a[],int n)//尾插法建立双向链表
{
	DulNode<DataType> *r;
	DulNode<DataType> *s;
    first=new DulNode<DataType>;

	r=first;
	for(int i=0;i<n;++i)
	{
		
		s=new DulNode<DataType>;
		
		s->data=a[i];
		s->prior=r;

		s->next=r->next;
	//	cout<<"sda"<<endl;
		r->next=s;
		//r->next=s;
		r=s;
		
	}
	cout<<"ok"<<endl;
}
template <class DataType>
void DoubleList<DataType>::Insert(int i,DataType x)
{
	DulNode<int>*p;
	DulNode<int>*s;

    p=first;
	 int count=1;

     while(p!=NULL||count<i)
	 {
		 p=p->next;
		 count++;
	 }
		 if(p==NULL)
			 throw"位置";
		 else{
			  s=new DulNode;
	          s->data=int x;
			  p->prior->next=s;
			  s->prior=p->prior;
			  p->prior=s;
			  s->next=p;
		 }
}
template <class DataType>
DataType DoubleList<DataType>::Delete(int i)//删除第i个元素
{
	DulNode<int>*p;
	
	//Node<int>*first;
     p=first->next;
	int count=1;

     while(p!=NULL||count<i)
	 {
		 p=p->next;
		 count++;
	 }
		 if(p==NULL||p->next==NULL)
			 throw"位置";
		 else
		 {
			 int	 x=p->data;
			 (p->prior)->next=p->next;
			 (p->next)->prior=p->prior;
		   
			 delete p;
			 return x;
		 }
}
template <class DataType>
void DoubleList<DataType>::PrintList()//遍历操作
{
	DulNode<int>*p;
	//Node<int>*first;

    p=first->next;
	while(p!=NULL)
	{	
		
		cout<<setw(2)<<p->data;
	    p=p->next;
	}
}
int main()
{
	//cout<<"请输入五位数字:"<<endl;
	int b[5]={1,2,3,4,5};
	
	DoubleList<int> L(b,5);
	cout<<"双链表创建完成"<<endl;
	L.PrintList();
	return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122

测试结果

在这里插入图片描述

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/427388
推荐阅读
相关标签
  

闽ICP备14008679号