编程练习——从尾到头打印链表

来源:互联网 发布:文华算法模型 编辑:程序博客网 时间:2024/06/05 17:31

题目描述

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

C++:借助于库函数

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(ListNode* head) {        vector<int>res;        if(head!=NULL){            res.insert(res.begin(),head->val);            while(head->next!=NULL){                head=head->next;                res.insert(res.begin(),head->val);                //head=head->next;            }        }        return res;    }};
C++:不借助库函数

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(ListNode* head) {        stack<int>s;        vector<int>res;        while(head){            s.push(head->val);            head=head->next;        }        while(s.size()){            //res.insert(res.end(),s.top());也行            res.push_back(s.top()); //表示把s.top()放到res的最后位置            s.pop();        }        return res;    }};

Python:

# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # 返回从尾部到头部的列表值序列,例如[1,2,3]    def printListFromTailToHead(self, listNode):        # write code here        l=[]        # head=listNode        while listNode:            l.insert(0,listNode.val)            listNode=listNode.next        return l

python:
# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = None class Solution:    # 返回从尾部到头部的列表值序列,例如[1,2,3]    def printListFromTailToHead(self, listNode):        # write code here        l = list()        while listNode:            l.append(listNode.val)            listNode = listNode.next        return l[::-1]