实现一个简单的学生链表

#include <string.h>#include <iostream>
using namespace std;

typedef struct SStudentNode
{
    int nID;//学号
    string strNmae;//姓名
    SStudentNode* pNextNode;
}SStudentNode,*pSStudentNode;

class CStudentLink
{
private:
    SStudentNode* m_pStudentLinkHeader;
public:
    CStudentLink();
    ~CStudentLink();
    int InsertStudentNode(int id,string name);
    int DelStudentNode(int id);
    int CorrectStudentNode(int id,string name);
    void DisplayStudent();
};
#include "Studentlink.h"
CStudentLink::CStudentLink()
{
    m_pStudentLinkHeader=NULL;
}

CStudentLink::~CStudentLink()
{
    SStudentNode* pTmp=NULL;
    while(NULL!=m_pStudentLinkHeader)
    {
        cout<<"start to delete all node"<<endl;
        pTmp=m_pStudentLinkHeader->pNextNode;
        cout<<"ID:"<<m_pStudentLinkHeader->nID<<endl;
        delete m_pStudentLinkHeader;
        m_pStudentLinkHeader=pTmp;
    }
}

int CStudentLink::InsertStudentNode(int id, string name)
{
    SStudentNode* pNewNode=new SStudentNode;
    pNewNode->nID=id;
    pNewNode->strNmae=name;
    pNewNode->pNextNode=NULL;//否则带来销毁的问题
    //插入队头
    if(NULL==m_pStudentLinkHeader)
    {
        m_pStudentLinkHeader=pNewNode;
        return 0;
    }

    pNewNode->pNextNode=m_pStudentLinkHeader;
    m_pStudentLinkHeader=pNewNode;
    return 0;
}

int CStudentLink::CorrectStudentNode(int id, string name)
{
    SStudentNode* pTmpNode=m_pStudentLinkHeader;
    while(NULL!=pTmpNode)
    {
        if(id==pTmpNode->nID)
        {
            pTmpNode->strNmae=name;
            return 0;
        }
        pTmpNode=pTmpNode->pNextNode;
    }
    return -1;

}

void CStudentLink::DisplayStudent()
{
    SStudentNode* pTmpNode=m_pStudentLinkHeader;
    while(NULL!=pTmpNode)
    {
        cout<<"id:"<<pTmpNode->nID<<"  ,name"<<pTmpNode->strNmae<<endl;
        pTmpNode=pTmpNode->pNextNode;
    }
}

int  CStudentLink::DelStudentNode(int id)
{
    //链表为空,返回
    if(NULL==m_pStudentLinkHeader)
    {
        return -1;
    }

    //尝试查询第一个元素
    if(id==m_pStudentLinkHeader->nID)
    {
        cout<<"delete ID:"<<m_pStudentLinkHeader->nID<<endl;
        delete m_pStudentLinkHeader;
        m_pStudentLinkHeader=m_pStudentLinkHeader->pNextNode;
        //m_pStudentLinkHeader==NULL;ERROR:后面可能还有元素
        return 0;
    }

    //如果下一个节点为空,返回
    if(NULL==m_pStudentLinkHeader->pNextNode)
    {
        return -2;
    }

    //如果第二个元素不为空,遍历第二元素
    SStudentNode* pTmpNode=m_pStudentLinkHeader;
    SStudentNode* pNextTmp=pTmpNode->pNextNode;
    while(NULL!=pNextTmp)
    {
        if(id==pNextTmp->nID)
        {
                pTmpNode->pNextNode=pNextTmp->pNextNode;
                cout<<"delete ID:"<<pNextTmp->nID<<endl;
                delete pNextTmp;
                pNextTmp=NULL;
                return 0;
        }
        pTmpNode=pNextTmp;
        pNextTmp=pNextTmp->pNextNode;
    }
    cout<<"Travser all node ,but not match"<<endl;
    return -3;
}

你可能感兴趣的:(链表)