国庆期间车管所上班吗:编一程序:①建立一个数据域为1至10的带头结点的链表;

来源:百度文库 编辑:高考问答 时间:2024/04/30 16:02:08
请各位达人给个解答,谢了先.用C语言的

#include <stdio.h>

//
//链表节点
//
struct Node
{
static Node * CreateNode(int nDat)
{
return new Node(nDat);
}
static void DeleteNode(Node *& pNode)
{
if (NULL != pNode)
{
delete pNode;
pNode=NULL;
}
}
Node(int nDat)
: m_pNext(NULL)
, m_pPrev(NULL)
, m_nData(nDat)
{}
Node *m_pPrev;
Node *m_pNext;
intm_nData;
private:
//
//forbid default construct
Node(){}
};

//
//双向链表
//
class Link
{
public:
Link()
: m_pHead(NULL)
, m_pTail(NULL)
{}
//
//前闭后开
//
Link(int nDatIn, int nDatOut)
: m_pHead(NULL)
, m_pTail(NULL)
{
AppendDatRange(nDatIn, nDatOut);
}
~Link()
{
ClearLink();
}
void AppendDatRange(int nIn, int nOut, bool bClrOrig = true)
{
if (nIn >= nOut)
{
return;
}
if (bClrOrig)
{
ClearLink();
}
for (int i = nIn; i < nOut; i ++)
{
AppendTail(Node::CreateNode(i));
}
}
void ReverseLink()
{
if (NULL == m_pHead)
{
return;
}
Node *pCurNode=m_pHead;
while (pCurNode)
{
Node *pOldPrev=pCurNode->m_pPrev;
Node *pOldNext=pCurNode->m_pNext;

pCurNode->m_pPrev=pOldNext;
pCurNode->m_pNext=pOldPrev;

pCurNode=pOldNext;
}
pCurNode=m_pHead;
m_pHead=m_pTail;
m_pTail=pCurNode;
}
void ClearLink()
{
if (NULL == m_pHead)
{
return;
}
Node *pCurNode=m_pHead;
while (pCurNode)
{
Node *pTmp=pCurNode;
pCurNode=pCurNode->m_pNext;
Node::DeleteNode(pTmp);
}
}
void PrintLink()
{
if (NULL == m_pHead)
{
printf("empty link\r\n");
return;
}
printf("data of link:\r\n");
Node *pCurNode=m_pHead;
while (pCurNode)
{
printf("%6d", pCurNode->m_nData);
pCurNode=pCurNode->m_pNext;
}
printf("\r\n");
}

protected:
void AppendTail(Node * pNode)
{
if (NULL == pNode)
{
return;
}
if (NULL == m_pTail)
{
m_pHead=pNode;
m_pTail=pNode;
}
else
{
m_pTail->m_pNext=pNode;
pNode->m_pPrev=m_pTail;
m_pTail=pNode;
}
}

private:
Node *m_pHead;
Node *m_pTail;
};

int main()
{
LinkcDoubleLink(1, 10);
printf("before reverse:\r\n");
cDoubleLink.PrintLink();

cDoubleLink.ReverseLink();
printf("after reversed:\r\n");
cDoubleLink.PrintLink();

return 0;
}

轻轻地我来了,给楼主带来了关注```
轻轻地我走了,给自己带走了积分```

楼主的问题,我也不清楚~~