剑指Offer面试题6:从尾到头打印链表

本文介绍了如何在C++中使用栈和递归的方法,从链表的尾部开始逆序打印每个节点的值,涉及ListNode结构、CreateLinkedList和PrintList函数实现。
摘要由CSDN通过智能技术生成

题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。链表节点定义如下:

struct ListNode
{
    int m_nkey;
    ListNode* m_pNext;
};

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

struct ListNode
{
	int m_nkey;
	ListNode* m_pNext;
};

ListNode* CreateLinkedList(vector<int> values)
{
    ListNode* head = nullptr;
    ListNode* tail = nullptr;

    for(int value : values)
    {
        ListNode* newNode = new ListNode;
        newNode->m_nkey = value;
        newNode->m_pNext = nullptr;

        if (head == nullptr)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail->m_pNext = newNode;
            tail = newNode;
        }
    }

    return head;
}

void PrintList(ListNode* pHead)
{
	std::stack<ListNode*> nodes;

	ListNode* pNode = pHead;
	while(pNode != nullptr)
	{
		nodes.push(pNode);
		pNode = pNode -> m_pNext;
	}
	
	while(! nodes.empty())
	{
		pNode = nodes.top();
		cout << pNode -> m_nkey <<" ";
		nodes.pop();
	}
}

int main()
{

	std::vector<int> nodeValues;
    nodeValues.push_back(1);
    nodeValues.push_back(2);
    nodeValues.push_back(3);
    nodeValues.push_back(4);
    nodeValues.push_back(5);
   
	ListNode* head = CreateLinkedList(nodeValues);
    PrintList(head);

	return 0;
}
void PrintList(ListNode* pHead)
{
	if(pHead != nullptr)
	{
		if(pHead->m_pNext != nullptr)
		{
			PrintList(pHead->m_pNext);
		}
		cout << pHead->m_nkey << " ";
	}
}

解题思路:这道题主要是针对链表的简单操作,不是很难,两种方法:栈&递归。

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值