剑指offer第三题 python java实现

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

class listNode:

    def __init__(self,x):
        self.val=x
        self.next=None
class Solution:
    def printListFromTailToHead(self,listNode):
        # if listNode==:
        #     return None

        array=[]

        cur=listNode


        while(cur):  #防止{}
            array.append(cur.val)
            cur=cur.next

        # array.sort(reverse=True)
        return array[-1::-1]
if __name__ == '__main__':
    Node1=listNode(5)
    Node2=listNode(7)
    Node3=listNode(1)
    Node4=listNode(3)
    Node1.next=Node2
    Node2.next=Node3
    Node3.next=Node4
    pro=Solution()
    print(pro.printListFromTailToHead(Node1))
    print(pro.printListFromTailToHead({}))



java实现


import java.util.ArrayList; import java.util.Random; import java.util.Scanner; import java.util.Stack;

class listNode{
    int val;
    listNode next=null;
    public listNode(int val){
        this.val=val;
    } } public class Solution {   public  ArrayList<Integer> printlistFromtailToHead(listNode listNode){
      Stack<Integer> stack=new Stack<Integer>();
      ArrayList<Integer> aList =new ArrayList<Integer>();
      while(listNode!=null){
         stack.push(listNode.val);
         listNode=listNode.next;
      }


      while(!stack.isEmpty()){

          aList.add(stack.pop());

      }
      return aList;   }
    public static String toString(listNode front){
        if(front==null)
            return "null";
        listNode curr=front;
        String str="[";
        while(curr.next !=null){
            str=str+curr.val+',';
            curr=curr.next;
        }
        str+=curr.val+"]";
        return str;

    }   public static void main(String []args){
      Random rnd=new Random();
      int listCount;
      Scanner keyIn=new Scanner(System.in );
      System.out.println("please Enter the size of the list:");
      listCount=keyIn.nextInt();

      listNode front=null,newNode;
      for(int i=0;i<listCount;i++){
          newNode=new listNode(rnd.nextInt(100));
          newNode.next=front;
          front=newNode;//单链表在表头插入新节点。

      }
      Solution pro=new Solution();
      System.out.println("Original list:");
      System.out.println(pro.toString(front));
      ArrayList<Integer> aList;
      aList=pro.printlistFromtailToHead(front);
      System.out.println("changed to arraylist is:");
      System.out.println(aList);


  } }

结果:

please Enter the size of the list: 5
Original list: [92,92,65,54,45]
changed to arraylist is: [45, 54, 65, 92, 92]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值