剑指offer面试题6:从尾到头打印链表
/*
输入一个链表的头结点从尾到头反过来打印每个结点的值
思路:一般不允许修改链表的值
1.先遍历的后输出,典型的先进后出,可以用栈去实现
2.每次都递归实现当前结点的后一个结点,虽然递归写代码会简洁很多,但是当链表比较长时就会使得调用的层级比较深,导致函数调用栈时溢出。
以下代码以思路一完成。
*/
# include <iostream>
template<typename T>
class List
{
public:
List()
{
phead = new Node();
}
~List()
{
Node* pCur = phead;
Node* pNext = pCur;
while(pCur != NULL)
{
pNext = pCur->pnext;
delete pCur;
pCur = pNext;
}
phead = NULL;
}
bool InsertTail(T val)//尾插法建立链表
{
Node* pnewnode = new Node(val);
Node* ptail = phead;
while(ptail->pnext != NULL)
{
ptail = ptail->pnext;
}
ptail->pnext = pnewnode;
return true;
}
void PrintListReversingly_Iteratively()//用栈存储链表的值
{
stack st;
Node* pCur = phead->pnext;
while(pCur != NULL)
{
st.push(pCur->mdata);
pCur = pCur->pnext;
}
st.show();
}
private:
class Node//节点类作为了链表类的嵌套类
{
public:
Node(T data = T()):mdata(data),pnext(NULL){}//初始化列表
friend class stack;//栈类作为了节点类的友元类
public:
T mdata;
Node* pnext;
};
class stack//栈类作为了链表类的嵌套类
{
public:
stack()
{
newsnode = new Node();
}
void push(T val)
{
Node* punode =new Node(val);
if(newsnode->pnext != NULL)
{
punode->pnext = newsnode->pnext;
}
newsnode->pnext = punode;
}
void pop()
{
Node* punode = newsnode->pnext;
newsnode ->pnext=punode->pnext;
delete punode;
}
void show()
{
Node* punode = newsnode->pnext;
while(punode != NULL)
{
std::cout<<punode->mdata<<" ";
punode = punode ->pnext;
}
std::cout <<std::endl;
}
public:
Node *newsnode;
};
Node* phead;
};
int main()
{
List<int> L;
L.InsertTail(1);
L.InsertTail(2);
L.PrintListReversingly_Iteratively();
List<double> L1;
L1.InsertTail(1.1);
L1.InsertTail(2.1);
L1.PrintListReversingly_Iteratively();
List<char *> L2;
char* a = "hello";
char* b = "world";
L2.InsertTail(a);
L2.InsertTail(b);
L2.PrintListReversingly_Iteratively();
return 0;
}