【每日一題】從尾到頭打印鏈表

題目:輸入鏈表的頭結點,從尾到頭反過來打印出每個結點的值。

解題思路:
  • 方法一:使用棧的方式輸出
  1. 根據給出的頭結點,從頭結點開始依次入棧;
  2. 將棧內的數據依次輸出。
  • 方法二:使用遞歸的方式輸出
  1. 構建函數輸出當前結點的值;
  2. 判斷當前結點是否爲空;
  3. 若當前結點不爲空,則在輸出當前結點值之前,調用自身,參數爲下一個結點。
public class Main03 {
	/**
	 * 定義結點對象
	 */
	public static class ListNode {
		// 結點值
		int val;
		// 下一個結點
		ListNode next;
	}

	/**
	 * 方法一:使用棧的方式進行輸出
	 * @param head 鏈表頭結點
	 */
	private static void printListInverselyUsingIteration(ListNode head) {
		Stack<ListNode> stack = new Stack<>();
		while (head != null) {
			stack.push(head);
			head = head.next;
		}
		while (!stack.isEmpty()) {
			System.out.print(stack.pop().val + " ");
		}
	}

	/**
	 * 方法二:使用遞歸的方式輸出
	 * @param head 鏈表頭結點
	 */
	private static void printListInverselyUsingRecursion(ListNode head) {
		if (head != null) {
			printListInverselyUsingRecursion(head.next);
			System.out.print(head.val + " ");
		}
	}

	public static void main(String[] args) {
		ListNode head = new ListNode();
		head.val = 1;
		head.next = new ListNode();
		head.next.val = 2;
		head.next.next = new ListNode();
		head.next.next.val = 3;
		head.next.next.next = new ListNode();
		head.next.next.next.val = 4;
		head.next.next.next.next = new ListNode();
		head.next.next.next.next.val = 5;

		// 方法一:使用遞歸的方式
		printListInverselyUsingIteration(head);

		System.out.println();

		//方法二:使用棧的方式
		printListInverselyUsingRecursion(head);
	}
}
運行結果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章