雙向鏈表

#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;
}

發佈了64 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章