c++单链表样例

#include "stdafx.h"
#include
using namespace std;
template
struct Node //定义结构体
{
	T data;
	Node *next;
};
template//定义模板类
class Linklist
{
public:
	Linklist();//无参构造函数
	Linklist(T a[], int i);//有参构造函数,i是数组长度
	~Linklist();
	int Length();//求单链表长度
	T Get(int i);//获取单链表中第i个位置的元素
	int Locate(T x);//获取元素为x的位置
	void Insert(T x, int i);//在第i个位置插入元素x
	T Delete(int i);//删除位置为i的元素
	void Printline();//遍历函数
private:
	Node *first=new Node;//定义头指针
};
//方法在类外的实现
template
Linklist::Linklist() {
	first = new Node;
	first->next = null;
}
template< class T>
Linklist::Linklist(T a[],int i) {
	Node *p=new Node;
	p = first;
	for (int j=0; j < i; j++) {
		Node *s = new Node;
		s->data = a[j];
		p->next = s;
		p = s;
	}
	p->next = NULL;
}
  template
  Linklist::~Linklist() {
	  while (first != NULL)
	  {
		  Node *p;
    	          p = new Node;
		  p = first;
		  first = first->next;
		  delete p;
	  }
  }
  template
int Linklist::Length()
  {
	  Node *p;
	  p = new Node;
	  p = first->next;
	  int count = 0;
	  while (p!=null)
	  {
		  p = p->next;
		  count++;
	  }
	  return count;
  }
  template
 T Linklist::Get(int i)
  {
	  Node *p;
      p = new Node;
	  p = first->next;
	  int count = 1;
	  while (p != NULL && count < i)
	  {
		  p = p->next;
		  count++;
	  }
	  if (p == NULL) throw "位置";
	  else return p->data;
  }
  template
 int  Linklist::Locate(T x)
  {
	  Node *p=new Node;
	  p = first->next;
	  int count = 1;
	  while (p != NULL)
	  {
		  if (p->data == x) return count;
		  p = p->next;
		  count++;
	  }
	  return 0;
  }
  template
void  Linklist::Insert(T x, int i)
  {
	  Node *p;
	  p = new Node;
	  p = first;
	  int count = 0;
	  while (p != NULL && count < i - 1)
	  {
		  p = p->next;
		  count++;
	  }
	  if (p == NULL)throw"位置";
	  else {
		  Node *s;
		  s = new Node;
		  s->data = x;
		  s->next = p->next;
		  p->next = s;
	  }
  }
  template
 T Linklist::Delete(int  i)
  {
	  Node *p=new Node;
	  p = first;
	  int count = 0;
	  while (p != NULL && count < i - 1)
	  {
		  p = p->next;
		  count++;
	  }
	  if (p == NULL || p->next == NULL) throw"位置";
	  else {
		  Node *q;
    	  q = new Node;
		  q = p->next; T x = q->data;
		  p->next = q->next;
		  delete q;
		  return x;
	  }
  }
  template
void  Linklist::Printline()
  {
	  Node *p=new Node;
	  p = first->next;
	  while (p != NULL)
	  {
		  cout << p->data;
		  p = p->next;
	  }
	  cout << endl;
  }
int main()
{
	int a[5] = {1,2,3,4,5};
	Linklist m = Linklist(a, 5);
	m.Printline();
	cout<

你可能感兴趣的:(数据结构)