更多题目可点链接:《剑指offer》目录索引
题目描述
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
思路:
递归打印
非递归
借助栈
具体过程可点链接:(http://blog.csdn.net/zhangye3017/article/details/78933001)
代码:
typedef struct SListNode
{
int _data;
struct SListNode* _next;
}SListNode;
SListNode* BuySListNode(int x)
{
SListNode* node = (SListNode*)malloc(sizeof(SListNode));
if (node == NULL)
{
perror("failue");
exit(EXIT_FAILURE);
}
node->_data = x;
node->_next = NULL;
return node;
}
void SListNodePushBack(SListNode** ppHead, int x)
{
if (*ppHead == NULL)
{
*ppHead = BuySListNode(x);
}
else
{
SListNode* tail = *ppHead;
while (tail->_next)
{
tail = tail->_next;
}
tail->_next = BuySListNode(x);
}
}
//递归
void SListPrintTailToHead(SListNode* pHead)
{
if (pHead == NULL)
return;
SListPrintTailToHead(pHead->_next);
printf("%d ", pHead->_data);
}
//循环
void SListPrintTailToHead1(SListNode* pHead)
{
if (pHead == NULL)
return;
SListNode* cur = NULL;
SListNode* tail = NULL;
while (tail != pHead)
{
cur = pHead;
while (cur->_next != tail)
{
cur = cur->_next;
}
printf("%d ", cur->_data);
tail = cur;
}
}
//借助栈
void SListPrintTailToHead2(SListNode* pHead)
{
stack<int>s;
SListNode* cur = pHead;
while (cur)
{
s.push(cur->_data);
cur = cur->_next;
}
while (!s.empty())
{
printf("%d ", s.top());
s.pop();
}
}
void Test1()
{
SListNode* list = NULL;
SListNodePushBack(&list, 6);
SListNodePushBack(&list, 5);
SListNodePushBack(&list, 4);
SListNodePushBack(&list, 3);
SListNodePushBack(&list, 2);
SListNodePushBack(&list, 1);
SListPrintTailToHead2(list);
}
int main()
{
Test1();
system("pause");
return 0;
}