JZ6 从尾到头打印链表[C++]

目录

题目

代码

 知识点


题目

输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。

如输入{1,2,3}的链表如下图:

返回一个数组为[3,2,1]

0 <= 链表长度 <= 10000

示例1

输入:

{1,2,3}

返回值:

[3,2,1]

示例2

输入:

{67,0,24,58}

返回值:

[58,24,0,67]

代码

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

struct Node
{
	int data;
	Node* next;
};

Node* Create(int n)
{
	Node* p, * h, * s;
	h = new Node;
	h->next = NULL;
	p = h;
	for (int i = 0; i < n; i++)
	{
		s = new Node;
		cin >> s->data;
		p->next = s;
		p = s;
	}
	p->next = NULL;
	return h;
}

void Print(Node* h)
{
	Node* p = h->next;
	while (p != NULL)
	{
		cout << p->data << "\t";
		p = p->next;
	}
	cout << endl;
}

vector<int>reverse(Node* h)
{
	Node* p = h->next;
	vector<int> ans;
	while (p != NULL)
	{
		ans.push_back(p->data);
		p = p->next;
	}
	reverse(ans.begin(), ans.end());
	for (vector<int>::iterator it = ans.begin(); it != ans.end(); it++)
	{
		cout << *it << "\t";
	}
	cout << endl;
	return ans;
}

int main()
{
	Node* head = new Node;
	head->next = NULL;
	int i;
	cout << "请输入单链表的个数:";
	cin >> i;
	cout << "请输入反转之前的链表结点:";
	head = Create(i);
	cout << "反转之后的链表结点是:";
	reverse(head);
	return 0;
}

运行结果:

 

 知识点

1.STL容器——vector以及reverse操作,STL容器的打印要依靠迭代器

for (vector<int>::iterator it = ans.begin(); it != ans.end(); it++)
	{
		cout << *it << "\t";
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值