其他分享
首页 > 其他分享> > 单链表

单链表

作者:互联网

#ifndef _LINKLIST_H_
#define _LINKLIST_H_
#include<iostream>
using namespace std;
template <typename T>
struct Node{
	T data;
	Node<T>* next;
};
template <typename T>
class linklist {
private:
	Node<T>* head;
	Node<T>* GetPtr(int i);
public:
	linklist();
	linklist(T* a, int n);
	linklist(linklist<T>& l);
	~linklist();
	int Length();
	bool Empty();
	void Clear();
	void PrintList();
	bool GetElem(int i, T& e);
	int Search(T e);
	bool Insert(int i, T e);
	bool Delete(int i, T& e);
};
template <typename T>
Node<T>* linklist<T>::GetPtr(int i) {
	if (i == 0)return head;
	Node<T>* p = head->next;
	int j = 1;
	while (j < i) {
		p = p->next;
		j++;
	}
	return p;
}

template <typename T>
linklist<T>::linklist() {
	head = new Node<T>;
	head->next = NULL;
}
template <typename T>
linklist<T>::linklist(T* a, int n) {
	head=new Node<T>;
	head->next = NULL;
	Node<T>* q = head;
	for (int i = 0; i < n; i++) {
	//new是开辟一块空间,将该空间地址赋值给P,也就是p指向开辟的空间
		Node<T> *p = new Node<T>;
		p->data = a[i];
		p->next = NULL;
		q->next = p;
		q = p;
	}
}
template <typename T>
linklist<T>::linklist(linklist<T>& l) {
	head = new Node<T>;
	head->next = NULL;
	T e;
	Node<T> *q = head, *p = NULL;
	for (int i = 1; i <= l.Length(); i++) {
		l.GetElem(i, e);
		p = new Node<T>;
		p->data = e;
		p->next = NULL;
		q->next = p;
		q = p;
	}
}
template <typename T>
linklist<T>::~linklist() {
	Clear();
	delete head;
}
template <typename T>
int linklist<T>::Length() {
	int j = 0;
	Node<T>* q = head->next;
	while (q != NULL) {
		j++;
		q = q->next;
	}
	return j;
}
template <typename T>
bool linklist<T>::Empty() {
	return head->next == NULL;
}
template <typename T>
void linklist<T>::Clear() {
	Node<T>* q = head->next;
	while (q) {
		head->next = q->next;
		delete q;
		q = head->next;
	}
}
template <typename T>
void linklist<T>::PrintList() {
	Node<T>* p = head->next;
	while (p != NULL) {
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}
template <typename T>
bool linklist<T>::GetElem(int i, T& e) {
	if (i<1 || i>Length())return false;
	Node<T>* p;
	p = GetPtr(i);
	e = p->data;
	return true;
}
template <typename T>
int linklist<T>::Search(T e) {
	Node<T>* p = head->next;
	int i = 1;
	while (p) {
		if (p->data == e)return i;
		p = p->next;
		i++;
	}
	return 0;
}
template <typename T>
bool linklist<T>::Insert(int i, T e) {
	if (i < 1 || i>Length() + 1)return false;
	Node<T>* q, * p;
	p = GetPtr(i-1);
	q = new Node<T>;
	q->data = e;
	q->next = p->next;
	p->next = q;
	return true;
}
template <typename T>
bool linklist<T>::Delete(int i, T& e) {
	if (i<1 || i>Length())return false;
	Node<T>* p = GetPtr(i - 1),*q;
	q = p->next;
	e = q->data;
	p->next = q->next;
	delete q;
	return true;
}
#endif

标签:Node,head,单链,int,next,linklist,template
来源: https://www.cnblogs.com/wxy214/p/16415208.html