从尾到头打印链表

仅作为个人笔记

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


C++

递归

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int>dev;
        if(head != NULL)
        {
            if(head -> next != NULL)
            {
                dev = printListFromTailToHead(head -> next);
            }
            dev.push_back(head -> val);
        }
        return dev;
    }
};

Java

递归

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    ArrayList<Integer> list = new ArrayList<>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {


        if(listNode != null)
        {
            this.printListFromTailToHead(listNode.next);
            list.add(listNode.val);
        }
        return list;
    }
}

利用栈

/**
*    public class Node {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
         Stack<Integer> stack = new Stack<>();
        while(listNode != null)
        {
            stack.push(listNode.val);
            listNode = listNode.next;
        }

        ArrayList<Integer> list = new ArrayList<>();
        while(!stack.isEmpty())
        {
            list.add(stack.pop());
        }

        return list;
    }
}

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 = []
        head = listNode
        while head:
            l.insert(0,head.val)
            head = head.next
        return l
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Shingle_/article/details/52347798
文章标签: 链表
个人分类: nowcoder
上一篇替换空格
下一篇重建二叉树
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭