zoukankan      html  css  js  c++  java
  • 剑指offer3 从头到尾打印链表

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

    package z_jzoffer.jz3;
    
    /**
     * @author houChen
     * @date 2020/8/18 11:24
     * @Description:
     */
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }
    package z_jzoffer.jz3;
    
    /**
     *输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
     */
    import java.util.ArrayList;
    import java.util.List;
    
    public class Solution3 {
    
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    
            //保存返回的结果
            ArrayList<Integer> list = new ArrayList<>();
    
            //获取链表的长度
            int len = 0;
            ListNode cur = listNode;
            while(cur!=null){
                len++;
                cur=cur.next;
            }
    
            //从后向前取出链表中的元素放入list中
            int count = 1; //计数器
            cur = listNode;
            while(true){
                if(len<1){
                    break; //链表中的元素取完了
                }
                if(count==len){ // 如果找到了第len个元素,就找len-1个元素
                    list.add(cur.val);
                    len--;
                    count=1;
                    cur=listNode;
                    continue;
                }
                count++;
                cur = cur.next;
            }
            return list;
        }
    }
    package z_jzoffer.jz3;
    
    import java.util.ArrayList;
    
    /**
     * @author houChen
     * @date 2020/8/18 11:40
     * @Description:
     */
    public class Solution3Test {
        public static void main(String[] args) {
            ListNode node1 = new ListNode(1);
            ListNode node2 = new ListNode(2);
            ListNode node3 = new ListNode(3);
            ListNode node4 = new ListNode(4);
            node1.next=node2;
            node2.next=node3;
            node3.next = node4;
    
            Solution3 s = new Solution3();
            ArrayList<Integer> list = s.printListFromTailToHead(node1);
            for(Integer ele : list){
                System.out.println(ele);
            }
        }
    }
  • 相关阅读:
    【HDOJ】2267 How Many People Can Survive
    【HDOJ】2268 How To Use The Car
    【HDOJ】2266 How Many Equations Can You Find
    【POJ】2278 DNA Sequence
    【ZOJ】3430 Detect the Virus
    【HDOJ】2896 病毒侵袭
    求奇数的乘积
    平方和与立方和
    求数列的和
    水仙花数
  • 原文地址:https://www.cnblogs.com/houchen/p/13532653.html
Copyright © 2011-2022 走看看