剑指offer第三天之从尾到头打印链表

剑指offer第三天之从尾到头打印链表
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
c++:
在这里插入图片描述
链表反转之后输出

class Solution {
public:
      ListNode* ReverseList(ListNode* pHead) {
        ListNode* r=NULL;
        ListNode* node=pHead;
        ListNode* p=NULL;
        while(node!=NULL)
        {
            r=node->next;
            node->next=p;
            p=node;
            node=r;
        }
        return p;
    }
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode* node = ReverseList(head);
        vector<int>v;
        while(node)
        {
            v.push_back(node->val);
            node=node->next;
        }
        return v;
    }
};

java:
在这里插入图片描述

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> arr= new ArrayList<>();
        while(listNode!=null)
        {
            arr.add(0,listNode.val);
            listNode =listNode.next;
        }
        return arr;
    }
}

python:
在这里插入图片描述

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        lista =[]
        while listNode:
            lista.insert(0,listNode.val)
            listNode=listNode.next
        return lista

java栈实现:
在这里插入图片描述

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> arr = new ArrayList<>();
        while(listNode!=null)
        {
            stack.push((Integer)listNode.val);
            listNode=listNode.next;
        }
        while(!stack.empty())
        {
            arr.add(stack.pop());
        }
        return arr;
    }
}

你可能感兴趣的:(剑指offer,列表,链表,java)