Offer 06:从尾部到头部打印链表

剑指Offer 06:从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)

示例 :
Input:head=[1,3,2]
Output:[2,3,1]

解题思路:
先定义链表,获取链表末尾,并删除;
*/

C++语言实现 

#include <iostream>
#include <list>
#include <vector>

using namespace std;

class Solution{
    public:
    vector<int> reversePrint(list<int> head){
        if(head.empty()){
            cout<<"链表为空.."<<endl;
            return {};
        }
        vector<int> result;
        auto n=head.size();
        while(n--){
            result.push_back(head.back());
            head.pop_back();
        };
        return result;
    }
};
int main(int argc,char* argv[]){
    list<int> head;
    head.push_back(1);
    head.push_back(3);
    head.push_back(2);
    vector<int> result=Solution().reversePrint(head);
    for(auto& res:result)
        cout<<res<<" ";
    cout<<endl;
    return 0;
}

Go语言实现 

 

package main

import (
	"container/list"
	"fmt"
)

func ReveserPrint(head list.List)[]interface{}{
	result:=make([]interface{},0)
	for it:=head.Front();it!=nil;it=it.Next() {
		result = append(result,it.Value)
	}
	return result
}

func main(){
	fmt.Println("从尾部到头打印链表(用数组或切片返回)")
	//head:=list.New()
	var head list.List
	head.Init()/*清空*/
	head.PushBack(1)
	head.PushBack(3)
	head.PushBack(2)
	fmt.Println(ReveserPrint(head))
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值