您的位置:首页 > 职场人生

剑指Offer面试题5[从尾到头打印链表]

2017-07-19 09:33 429 查看

1. 题目描述:

输入一个链表的头结点,从尾到头打印链表每个节点的值。

2. 相关知识:

循环、递归、栈

3. 解答思路:

思路1,将链表压入栈中,后进先出实现从尾到头打印。

思路2,采用递归的方法,但如果链表很长会导致栈溢出。

4. 代码实现:

C/C++语言实现

#include "stdafx.h"
#include <stack>
using namespace std;

struct ListNode {
int val;
struct ListNode *next;
};

void printListFromTailToHead(ListNode* head) {
stack<ListNode *> nodes;
ListNode *pNode = head;
while(pNode!=NULL)
{
nodes.push(pNode);
pNode = pNode->next;
}
while(!nodes.empty())
{
pNode = nodes.top();
printf("%d\t",pNode->val);
nodes.pop();
}
}

void Recursive_print(ListNode* head) {
if(head!=NULL)
{
if(head->next != NULL)
{
Recursive_print(head->next);
}
printf("%d\t",head->val);
}
}

struct ListNode *make_node(int val)
{
struct ListNode *node = (ListNode*) malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
}

int _tmain(int argc, _TCHAR* argv[])
{
struct ListNode *head = NULL;
struct ListNode *pNode = NULL;
struct ListNode *node = NULL;
node = make_node(1);
head = node;
pNode = node;
node = make_node(2);
pNode->next = node;
pNode = node;
node = make_node(3);
pNode->next = node;
pNode = node;
node = make_node(4);
pNode->next = node;
pNode = node;

Recursive_print(head);
printListFromTailToHead(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题