Java链表学习记录 | 剑指offer 从尾到头打印链表

1.定义一个简单链表

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

2.链表操作: 新增、遍历展示

public class Solution{
    private ListNode head;
    //向链表末尾增加元素
    public void addEle(int val) {
        //如果头节点为空,则新建头节点
        if (head == null) {
            head = new ListNode(val);
        } else {
        //头节点不为空,则复制一份链表,将复制的链表指针移到链表尾部。
            ListNode listNode = head;
            while (listNode.next != null) {
                listNode = listNode.next;
            }
            listNode.next = new ListNode(val);
        }
    }
    public void show() {
        if (head == null) {
            System.out.println("Link is empty.");
        } else {
            ListNode listNode = head;
            while (listNode != null) {
                System.out.println("val is:   " + listNode.val);
                listNode = listNode.next;
            }
        }
    }
}

3.结果展示

public static void main(String[] args) {
        Solution so = new Solution();
        so.addEle(3);
        so.addEle(7);
        so.addEle(32);
        so.addEle(89);
        so.show();
    }

结果1

4.牛客剑指offer题目 从尾到头打印链表

从尾到头打印链表

4.1方法一:

思路:利用栈先进后出的特点,将链表中的元素放入栈中,再遍历栈放入Array List中

 public ArrayList<Integer> printListFromTailToHead() {
        ArrayList<Integer> res = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        if(head==null){
            return res;
        }
        ListNode listNode = head;
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
       while(!stack.empty()){
            res.add(stack.pop());
        }
        return res;
    }
4.2 方法2:

利用ArrayList.add(0,val);

   public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
        //method 1: use
        ArrayList<Integer> arrayList = new ArrayList<>();
        while (listNode != null) {
            arrayList.add(0,listNode.val);
            listNode = listNode.next;
        }
        return arrayList;
    }
4.3 方法3:

利用递归
效率不高

 public ArrayList<Integer> printListFromTailToHead3(ListNode listNode) {
        if (listNode != null) {
            printListFromTailToHead3(listNode.next);
            arrayList.add(listNode.val);
        }
        return arrayList;
    }

努力,进取,奋斗!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小雅痞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值