编程语言
首页 > 编程语言> > 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);
	}

}

标签:从头到尾,val,listNode,next,链表,Java,new,ListNode,public
来源: https://blog.csdn.net/weixin_43206161/article/details/121734894