#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;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交