Home >Java >javaTutorial >Example analysis of Java implementation of printing linked list from end to beginning
This article mainly introduces Java programming to implement an example of printing a linked list code from the end to the beginning. The editor thinks it is quite good, so I will share it with you here for the reference of friends who need it.
Problem description: Enter the head node of a linked list, and print the value of each node in reverse from the tail to the head.
First define the linked list nodes
public class ListNode { int val; ListNode next = null; ListNode(int val){ this.val = val; } }
Idea 1: This question obviously uses the idea of the stack, last in first out, First traverse the linked list and push the node values onto the stack in sequence. Finally, pop the stack after traversing the stack.
public static Stack<Integer> printListReverse_Stack(ListNode listNode){ Stack<Integer> stack = new Stack<Integer>(); if(listNode != null){ ListNode p = listNode; while(p != null){ stack.add(p.val); p = p.next; } } return stack; }
Idea 2: Traverse the linked list directly and insert it into the ArrayList sequentially according to the head insertion method
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode){//表头也存储元素 ArrayList<Integer> print = new ArrayList<Integer>(); if(listNode == null){ return print; } int add = 0; ListNode p = listNode; while(p != null){ print.add(0, p.val); p = p.next; } return print; }
Idea 3: You can use the idea of recursion (the essence is also the idea of stack)
public ArrayList<Integer> printListReversely_Recursively(ListNode listNode){ ArrayList<Integer> print = new ArrayList<Integer>(); if(listNode == null){ return print; } print.addAll(printListReversely_Recursively(listNode.next)); print.add(listNode.val); return print; }
Summary
The above is the detailed content of Example analysis of Java implementation of printing linked list from end to beginning. For more information, please follow other related articles on the PHP Chinese website!