#pragma once
#include "stdafx.h"
template<class T>
class CLinkList
{
public:
typedef struct LNode{
T data;
struct LNode * next;
}LNode;//单向链表
LNode * list;//头指针
CLinkList()
{
length=0;
list=new LNode;
list->next=NULL;//头指针data不赋值
}
void Add(T data)
{
length++; //元素增加
LNode * now=list;
while(now->next) now=now->next;
LNode * tmp=new LNode;
tmp->next=NULL;
tmp->data=data;
now->next=tmp;
}
void Delete(int index)
{
if(index<0) return;//防止下溢
int i=0;
LNode * now=list;
while(now->next && i<index) //防止上溢
{
now=now->next;
i++;
}
if(now->next)//防止上溢
{
length--; //元素减少
LNode * del=now->next;
now->next=del->next;
delete del;
}
}
void Insert(int index,T data)
{
if(index<0) return;//防止下溢
int i=0;
LNode * now=list;
while(now->next && i<index) //防止上溢
{
now=now->next;
i++;
}
if(now->next)//防止上溢
{
length++; //元素增加
LNode * tmp=new LNode;
tmp->next=now->next;
tmp->data=data;
now->next=tmp;
}
}
T GetAt(int index)
{
if(index<0) return list->next->data;//防止下溢
int i=0;
LNode * now=list;
while(now->next && i<index) //防止上溢
{
now=now->next;
i++;
}
return now->next->data;
}
void SetAt(int index,T data)
{
if(index<0) return;//防止下溢
int i=0;
LNode * now=list;
while(now->next && i<index) //防止上溢
{
now=now->next;
i++;
}
now->next->data=data;
}
/*
T * GetRange(int a,int b)
{
}*/
T operator [] (int index)
{
return GetAt(index);
}
int GetLen(){return length;}
void display()
{
LNode * now=list->next;
while(now)
{
printf("%d,",now->data);
now=now->next;
}
printf("\n");
}
protected:
private:
int length;
};