最近整理原来的博文,数据结构和算法,笔试题,眼泪哗哗的,网申开始。
废话少说,这次实现的单链表类:
//list.h
#ifndef _LIST_H_
#define _LIST_H_
#ifndef NULL
#define NULL 0
#endif
//C++实现单链表
template<class T>
struct node
{
T data;
node<T> *next;
node():next(NULL){}
node(T d):next(NULL),data(d){}
};
template<class T>
class link_list
{
public:
link_list();
link_list(T a[], int len);//initialize the list using array a
~link_list();
int get_length() const;//get the length of the list
T get_node(int pos) const;// get the node in position pos
bool delete_node(int pos);//delete the node in position pos
bool insert_node(int pos, T data);//insert data in pos
void print_list() const;//print the list
private:
node<T> *head; //the head of the list, don't store any data in head node
};
//list.cpp文件,需要说明的是list的头指针的data域保存的是list的长度,其他没啥
template<class T>
link_list<T>::link_list()
{
head = new node<T>;
head->data = 0;
}
template<class T>
link_list<T>::link_list( T a[], int len )
{
//insert from the head
head = new node<T>;
head->data = len;
node<T>* p = head;
for (int i = 0; i < len; i++)
{
node<T>* p_node = new node<T>;
p_node->data = a[i];
p->next = p_node;
p = p_node;
}
//insert from the tail
//head = new node<T>;
//head->data = len;//头结点数据域存储list长度
//node<T>* p = head;
//for (int i = 0; i < len; i++)
//{
// node<T>* p_node = new node<T>;
// p_node->data = a[i];
// p_node->next = p->next;//保证最后一个节点的next域为NULL
// p->next = p_node;
//}
}
template<class T>
link_list<T>::~link_list()
{
node<T>* p = head;
node<T>* q;
while(p)
{
q = p;
p = p->next;
delete q;
}//保证能够完全释放资源
}
template<class T>
int link_list<T>::get_length() const
{
return head->data;
}
template<class T>
T link_list<T>::get_node( int pos ) const
{
node<T>* pnode = head->next;
assert(pos > 0 && pos <= head->data);
int i = 1;
while(i++ != pos && pnode )
{
pnode = pnode->next;
}
return pnode->data;
}
template<class T>
bool link_list<T>::delete_node( int pos )
{
node<T>* pnode = head->next;
int i = 1;
assert(pos > 0 && pos <= head->data);
while(i++ != (pos-1) && pnode )//这里不是pos,是要招删除节点的前一个节点
{
pnode = pnode->next;
}
node<T>* q = pnode->next;
pnode->next = q->next;
T m = q->data;
delete q;
head->data--;
return m;
}
template<class T>
bool link_list<T>::insert_node( int pos, T data )
{
//在pos位置之前插入data
if (pos <= 0 || pos >= head->data)
return false;
else
{
node<T>* pnode = head->next;
int i = 1;
while(i++ != (pos-1) && pnode)
{
pnode = pnode->next;
}
node<T>* q = new node<T>;
q->data = data;
q->next = pnode->next;
pnode->next = q;
head->data++;//长度变长
return true;
}
}
template<class T>
void link_list<T>::print_list() const
{
node<T>* p = head->next;
while(p)
{
cout<<p->data<<endl;
p = p->next;
}
}
#include "list.h"
#include <iostream>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5};
link_list<int> m_list(a, 5);
m_list.print_list();
m_list.get_node(1);
m_list.delete_node(3);
m_list.print_list();
m_list.insert_node(3,10);
m_list.print_list();
}