剑指offer66题--Java实现,c++实现和python实现 3.从尾到头打印链表

题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
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> stack;
        vector<int> vector;
        struct ListNode* p=head;
        if(head!=NULL)//头不为空
        {
            stack.push(p->val);//将头入栈
            while((p=p->next)!=NULL)//遍历链表
            {
                stack.push(p->val);//将链表元素压入栈中
            }
            while(!stack.empty())//当栈不为空
            {
                vector.push_back(stack.top());//在vector类中作用为在vector尾部加入一个数据。
                stack.pop();//出栈
            }
        }
        return vector;
    }
};

Java实现

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;//导入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> arraylist=new ArrayList<Integer>();//创建一个ArrayList
        while(!stack.isEmpty())//
        {
            arraylist.add(stack.pop());//将每一个出栈的元素通过add()添加到arraylist中
        }
        return arraylist;
    }
}

python实现

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
 
class Solution:
    def printListFromTailToHead(self, listNode):
        # write code here
        out=[]#创建一个列表
        head = listNode#将节点赋值给head
        while head!=None:#当head不为空时循环
            out.append(head.val)#将head的值通过append()加到列表中
            head=head.next
        out.reverse()#列表反转
        return out

猜你喜欢

转载自blog.csdn.net/walter7/article/details/84137180