Java教程

Java从头到尾打印链表

本文主要是介绍Java从头到尾打印链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/**
 * @author kegekeqi
 * @version 1.0
 * @date 2021-12-5 14:18
 */
public class ListNode {
	int val;
	ListNode next;

	public int getVal() {
		return val;
	}

	public void setVal(int val) {
		this.val = val;
	}

	public ListNode getNext() {
		return next;
	}

	public void setNext(ListNode next) {
		this.next = next;
	}

	@Override
	public String toString() {
		return "ListNode{" +
				"val=" + val +
				", next=" + next +
				'}';
	}
}
import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @author kegekeqi
 * @version 1.0
 * @date 2021-12-5 14:16
 */
public class ChapterTwo {
	//链表从头到尾输出来
	public LinkedList<Integer> printByTail(ListNode listNode) {
		LinkedList<Integer> result = new LinkedList<>();
		if (null == listNode) {
			return result;
		}
		LinkedList<Integer> stack = new LinkedList<>();
		while (null != listNode) {
			stack.add(listNode.val);
			listNode = listNode.next;
		}
		for (int i = stack.size() - 1; i >= 0; i--) {
			result.add(stack.get(i));
		}
		return result;
	}

	public static void main(String[] args) {
		ChapterTwo chapterTwo = new ChapterTwo();
		ListNode listNode = new ListNode();
		listNode.setVal(1);
		ListNode listNode1 = new ListNode();
		listNode1.setVal(3);
		listNode.setNext(listNode1);
		ListNode listNode2 = new ListNode();
		listNode2.setVal(89);
		listNode1.setNext(listNode2);
		ListNode listNode3 = new ListNode();
		listNode3.setVal(9);
		listNode2.setNext(listNode3);
		ListNode listNode4 = new ListNode();
		listNode4.setVal(34);
		listNode3.setNext(listNode4);
		System.out.println(listNode);
		LinkedList<Integer> integers = chapterTwo.printByTail(listNode);
		System.out.println("===================");
		System.out.println(integers);
	}

}

这篇关于Java从头到尾打印链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!