双向链表

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

typedef unsigned int UINT;

template <class Type>
struct Node{
	Type data;
	Node* prev;
	Node* next;
	Node(Type val=NULL):next(NULL),data(val){}
};

template <class Type>
class List{
public:
	UINT length;
	List();
	void push_back(Type val);
	void push_front(Type val);
	int search(Type val); //搜索到返回下标,否则返回-1
	int del(UINT index); //如果下标存在则删除下标位置元素返回0,否则返回-1
	void toString();
	
private:
	Node<Type>* head;
	
};
//构造函数
template <class Type>
List<Type>::List(){
	head=new Node<Type>;
	head->prev=NULL;
	length=0;
}
//尾部追加
template <class Type>
void List<Type>::push_back(Type val){
	Node<Type>* p=head;
	while(p->next != NULL) p=p->next;
	p->next=new Node<Type>(val);
	p->next->prev=p;
	length++;
}
//首部追加
template <class Type>
void List<Type>::push_front(Type val){
	Node<Type>* p=new Node<Type>(val);
	p->prev=head;
	p->next=head->next;
	p->next->prev=p;
	head->next=p;
	length++;
}
//查找元素
template <class Type>
int List<Type>::search(Type val){
	Node<Type>* p=head;
	int index=0;
	while(p->next!=NULL){
		p=p->next;
		if(p->data==val) return index;
		index++;
	}
	return -1;
}
//删除元素
template <class Type>
int List<Type>::del(UINT index){
	if (head->next==NULL || index<0 || index>length-1) return -1;
	Node<Type>* p=head->next;
	while(index--) p=p->next;
	if(p->next != NULL){
		p->prev->next=p->next;
		p->next->prev=p->prev;
	}else p->prev->next=NULL;
	length--;
	return 0;
}
//显示链表
template <class Type>
void List<Type>::toString(){
	Node<Type>* p=head;
	cout<<"[";
	while(p->next != NULL){
		p=p->next;
		cout<<p->data;
		if (p->next != NULL) cout<<", ";
	}
	cout<<"]"<<endl;
}


//测试
int _tmain(int argc, _TCHAR* argv[])
{
	List<int> list;
	list.push_back(1);
	list.push_back(2);
	list.push_back(3);
	list.push_front(4);
	list.del(2);
	list.push_back(5);
	list.toString();
	cout<<list.length<<endl;
	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值