Home > Java > javaTutorial > Example analysis of Java implementation of printing linked list from end to beginning

Example analysis of Java implementation of printing linked list from end to beginning

黄舟
Release: 2017-10-16 09:51:59
Original
1394 people have browsed it

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;
    }
  }
Copy after login

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;
  }
Copy after login

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;
  }
Copy after login

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;
  }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template