剑指offer 5---从尾到头打印单链表

从尾到头打印单链表

PS:

如果题设不要求不能改变链表结构时,可以使用单链表的逆置(之前已经写过),单链表的逆置改变了链表的方向,严格要求时不能这样写。

解1:递归求解

//从尾到头打印单链表--递归实现
ListNode* PrintList(ListNode* pHead)
{
	if (pHead == NULL)
	{
		return NULL;
	}
	ListNode* cur = pHead;
	if (cur->_next != NULL)
	{
		PrintList(cur->_next);
	}
	cout << cur->_value << "->";
}

int main()
{
	ListNode* pHead = new ListNode(1);
	ListNode* cur = pHead;
	ListNode* p = pHead;
	for (int i = 2; i <= 10; ++i)
	{
		ListNode* temp = new ListNode(i);
		cur->_next = temp;
		cur = temp;
	}
	PrintList(pHead);
	system("pause");
	return 0;
}




解2:非递归实现---利用栈的特性:先进的后出

ListNode* PrintList(ListNode* pHead)
{
	if (pHead == NULL)
	{
		return NULL;
	}
	ListNode* p = pHead;	
	stack<ListNode*> q;     //一个元素类型为ListNode* 的栈
	while (p)
	{
		q.push(p);
		p = p->_next;
	}
	while (q.size())
	{
		cout << q.top()->_value << "->";
		q.pop();
	}
}

int main()
{
	ListNode* pHead = new ListNode(1);
	ListNode* cur = pHead;
	ListNode* p = pHead;
	for (int i = 2; i <= 10; ++i)
	{
		ListNode* temp = new ListNode(i);
		cur->_next = temp;
		cur = temp;
	}
	PrintList(pHead);
	system("pause");
	return 0;
}


在线编译代码:   利用vector

//从尾到头打印单链表
#include <iostream>
#include <stack>
#include <vector>
#include <Windows.h>
using namespace std;

struct ListNode
{
	int _value;
	ListNode* _next;
	ListNode(const int& value)
		:_value(value)
		, _next(NULL)
	{}
};

vector<int> Print(ListNode* head)
{
	vector<int> tty;
	stack<int> zzp;
	ListNode* p = head;
	while (p != NULL)
	{
		zzp.push(p->_value);
		p = p->_next;
	}
	while (!zzp.empty())
	{
		tty.push_back(zzp.top());
		zzp.pop();
	}
	return tty;
}

int main()
{
	ListNode* head = new ListNode(1);
	ListNode* p = head;
	ListNode* cur = head;
	for (int i = 2; i <= 10; ++i)
	{
		ListNode* temp = new ListNode(i);
		cur->_next = temp;
		cur = temp;
	}
	while (p)
	{
		cout << p->_value << "->";
		p = p->_next;
	}
	cout << endl;
	vector<int> cc = Print(head);
	for (int j = 0; j < cc.size(); ++j)
	{
		cout << cc[j] << "->";
		
	}
	system("pause");
	return 0;

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值