前几天面试的一道题,尼玛在纸上写各种不爽,我只想说 我去年买了个表。。
好吧,花了点时间写了下。
直接上代码:
#include <stdio.h>
struct LinkNode
{
LinkNode(): m_Value(-1)
, m_pPreNode(NULL)
, m_pNextNode(NULL)
{
}
int m_Value;
LinkNode* m_pPreNode;
LinkNode* m_pNextNode;
};
class Stack
{
public:
void Init()
{
m_pHeadNode = new LinkNode();
m_Size = 0;
}
void Pop()
{
if (m_pHeadNode->m_pPreNode == m_pHeadNode)
{
return ;
}
LinkNode* lpNode = m_pHeadNode->m_pPreNode;
m_pHeadNode->m_pPreNode = lpNode->m_pPreNode;
lpNode->m_pPreNode->m_pNextNode = m_pHeadNode;
delete lpNode;
lpNode = NULL;
}
int Top()
{
int lTop = m_pHeadNode->m_pPreNode->m_Value;
printf("top:%d\n",lTop);
return lTop;
}
void Push(int aValue)
{
LinkNode* lpNewNode = new LinkNode();
lpNewNode->m_Value = aValue;
LinkNode* lpNode = m_pHeadNode->m_pNextNode;
if (NULL == lpNode)
{
m_pHeadNode->m_pNextNode = lpNewNode;
lpNewNode->m_pPreNode = m_pHeadNode;
lpNewNode->m_pNextNode = m_pHeadNode;
m_pHeadNode->m_pPreNode = lpNewNode;
}
else
{
while(lpNode)
{
if (m_pHeadNode == lpNode->m_pNextNode )
{
break;
}
lpNode = lpNode->m_pNextNode;
}
lpNode->m_pNextNode = lpNewNode;
lpNewNode->m_pPreNode = lpNode;
lpNewNode->m_pNextNode = m_pHeadNode;
m_pHeadNode->m_pPreNode = lpNewNode;
}
}
void Print()
{
LinkNode* lpNode = m_pHeadNode->m_pNextNode;
while(lpNode)
{
if (lpNode == m_pHeadNode)
{
break;
}
printf("%d ",lpNode->m_Value);
lpNode = lpNode->m_pNextNode;
}
}
private:
LinkNode* m_pHeadNode;
};
int main()
{
Stack lStack;
lStack.Init();
lStack.Push(1);
lStack.Push(2);
lStack.Push(4);
lStack.Top();
lStack.Pop();
lStack.Top();
lStack.Print();
}