剑指offer:从尾到头打印链表

一、题目描述

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

二、实现代码

//这部分结构体定义提前已经给出
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/


class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {

        //先通过迭代的方式,将链表实现反转
        ListNode* Newh = NULL;
        for(ListNode* p=head;p;){
            ListNode* temp = p->next;
            p->next=Newh;
            Newh=p;
            p=temp;
        }

        //读取翻转链表中每个节点的值,存入到vector中,并返回
        ListNode* p2=Newh;
        while(p2!=NULL){
            result.push_back(p2->val);
            p2=p2->next;
        }
        return result;
    }
};

三、代码笔记

猜你喜欢

转载自blog.csdn.net/yph001/article/details/80740755
今日推荐