[文档整理系列] 线性链表之单链表
/*
问题描述:线性表____链表_____单链表
@date 2017-3-7
*/
#include<iostream>
using namespace std;
template<typename T>
struct node{
T data;
node<T> *next;
};
template<typename T>
class LinkedList{
public:
LinkedList();
LinkedList(T arr[],int n);
~LinkedList();
int getLength();
void InsertAt(int n,T data);
T DeleteAt(int i);
T GetData(int i);
int getDataAt(T data);
void Print();
private:
int length;
node<T> *first;
};
template <class T>
LinkedList<T>::LinkedList(){
first = new node<T>;
first->next = NULL;
length = 0;
}
template <class T>
LinkedList<T>::LinkedList(T arr[],int n){
first = new node<T>(); //初始化指针变量
first->next = NULL;
for(int i = 0;i<n;i++){
node<T> s;
s.data = arr[i];
s.next = first->next;
first->next = &s;
}
length = n;
cout<<"初始化成功!"<<endl; //test
}
template<typename T>
LinkedList<T>::~LinkedList(){
node<T> *q;
while (first) //释放单链表的每一个结点的存储空间
{
q=first; //暂存被释放结点
first=first->next; //工作指针p指向被释放结点的下一个结点,使单链表不断开
delete q;
}
cout<<"析构(销毁)成功!"<<endl; //test
}
template<typename T>
int LinkedList<T>::getLength(){
return length;
}
template< typename T>
void LinkedList<T>::InsertAt(int n,T data){
cout<<"成功插入第"<<n<<"个位置!"<<endl;
}
int main(){
int arr[6]={7,19,4,5,6,9};
LinkedList<int> t(arr,6);
// t.InsertAt(7,689);
return 0;
}