代码结构:
SingleListTest.cpp:验证功能。
SingleList.h:声明定义链表。
SingleList.h:
#pragma once
#ifndef H_SINGLELIST_H
#define H_SINGLELIST_H
#include <iostream>
#include<string>
using namespace std;
template <class T>
struct Node{
T content;
Node* pNext;
Node()
{
content = 0;
pNext = NULL;
}
};
template <class T>
class SingleList {
private:
Node<T>* pHead;
int m_lenth;
public:
void InsertNode(int pos,T content);
Node<T>* Find(T content) const;
Node<T>* FindPosNode(int pos) const;
Node<T>* FindLast() const;
void PrintList() const;
void Delete(int pos);
SingleList(int m = 0);
~SingleList();
};
template <class T>
SingleList<T>::SingleList(int m)
{
Node<T>* node;
Node<T>* lastnode=NULL;
for (int i = 0; i < m; i++)
{
node = new Node<T>;
if (i == 0)
{
pHead = node;
}
else
{
lastnode->pNext = node;
}
lastnode = node;
m_lenth++;
}
}
template <class T>
SingleList<T>::~SingleList()
{
//delete[] pHead;
Node<T>* ptmp;
for (Node<T>* p = pHead; p != NULL; )
{
ptmp = p->pNext;
delete p;
p = ptmp;
}
}
template <class T>
Node<T>* SingleList<T>::FindLast() const
{
for (Node<T>* p = pHead;; p = p->pNext)
{
if (p->pNext == NULL)
{
return p;
}
}
return NULL;
}
template <class T>
void SingleList<T>::InsertNode(int pos, T content)
{
if (m_lenth < pos)
{
cout << "List Do no have so many node,now:"<<m_lenth << endl;
return;
}
Node<T>* padd = new Node<T>;
if (padd == NULL)
{
cout << "new failed.\n";
return;
}
Node<T>* pcur = FindPosNode(pos);
padd->pNext = pcur->pNext;
pcur->pNext = padd;
padd->content = content;
m_lenth++;
return;
}
template <class T>
Node<T>* SingleList<T>::FindPosNode(int pos) const
{
if (pos > m_lenth)
{
cout << "not long enough" << m_lenth << "<<\n";
}
Node<T> *p = pHead;
for (; pos > 0; pos--)
{
p = p->pNext;
}
return p;
}
template <class T>
Node<T>* SingleList<T>::Find(T content) const
{
for (Node<T>* p = pHead;p!=NULL; p = p->pNext)
{
if (p->content == content)
{
return p;
}
}
return NULL;
}
template <class T>
void SingleList<T>::PrintList() const
{
int m = 0;
cout << "length:" << m_lenth<< endl;
for (Node<T>* p = pHead; p != NULL; p=p->pNext)
{
cout << "N.O[" << m++ << "] element[" << p->content << "]" << endl;
}
return;
}
template <class T>
void SingleList<T>::Delete(int pos)
{
Node<T>* pcur = FindPosNode(pos);
Node<T>* ppre = FindPosNode(pos - 1);
ppre->pNext = pcur->pNext;
delete pcur;
m_lenth--;
}
#endif
SingleListTest.cpp:
// SingleListTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include"SingleList.h"
#include<fstream>
#include<string>
using namespace std;
int main()
{
SingleList<int> list(3);
list.InsertNode(1,20);
list.Delete(1);
list.InsertNode(2, 30);
list.PrintList();
if (list.Find(30) != NULL)
{
cout<<"Find 30 in:"<<list.Find(30)->content<<endl;
}
cin.get();
return 0;
}
由于链表是存储结构上不连续的存储结构,因此不能采用new Node[n]这种形式,因此还是老老实实一个元素一个元素得新建和删除好了。