最近看一本书上有求链表的倒数第N个节点,简单实现了下 链表,实现方案如下
1、不借助链表长度顺序遍历倒数第N个节点 GetReserveN就是如此实现。
2、当然如果链表记录了节点长度也可以直接正序遍历出来 第lenth-N个节点就是倒数节点。
template<class T> class LinkedList { public: operator T(){return m_data;} virtual ~LinkedList() { if(m_size!=0) Clear(); } void AddData(T data) { if(m_size==0) { m_data=data; } else { LinkedList<T>* pTem=new LinkedList<T> ; pTem->m_data=data ; pTem->m_pPrev=this->m_pTail ; pTem->m_pNext=0; this->m_pTail->m_pNext=pTem; this->m_pTail=pTem; } m_size++; } void SetData(T data) { m_data=data; } void Clear() { LinkedList<T>*pTem=this->Next(); LinkedList<T>*pDel; for(; pTem;) { pDel=pTem; pTem=pTem->Next(); delete pDel; } m_pTail=this; m_pPrev=this; m_size=0; } int Size() { return m_size; } T GetData() { return m_data ; } LinkedList<T>*Next() { return m_pNext; } LinkedList<T>*GetTail() { return m_pTail; } LinkedList<T>*GetPrevious() { return m_pPrev; } LinkedList<T>* GetReserveN(int n) { if(n>m_size||n<=0) return 0; LinkedList<T>*pFront=this; LinkedList<T>*pBehand=this; for(int i=1; i<=n; i++) { pBehand=pBehand->Next(); } while(true) { if(pBehand==0) return pFront ; pBehand=pBehand->Next(); pFront=pFront->Next(); } } static LinkedList<T>* CreateList() { return new LinkedList<T>; }; private: LinkedList():m_pNext(0),m_pPrev(0),m_pTail(0),m_size(0) { m_pTail=this; m_pPrev=this; } LinkedList<T>*m_pNext; LinkedList<T>*m_pTail; LinkedList<T>*m_pPrev; int m_size; T m_data; };
测试代码如下
#include <iostream> #include<string> #include "LinkedList.h" using namespace std; int main() { LinkedList<string> *pTem=LinkedList<string>::CreateList(); pTem->AddData("xxx"); pTem->AddData("dsdf"); pTem->AddData("dfsd"); pTem->AddData("dseee"); pTem->AddData("xxxx"); pTem->AddData("dsfdsf"); pTem->AddData("fdsfd"); LinkedList<string>*p=pTem ; for(; p;) { cout<<p->GetData()<<"," ; p=p->Next(); } cout<<endl; LinkedList<string>*pData=pTem->GetReserveN(5); if(pData) cout<<"Reserve N:"<<pData->GetData()<<endl; else{ cout<<"Reserver Not Found !"<<endl; } return 0; }
时间: 2024-10-27 10:13:02