【劍指Offer】從尾到頭列印連結串列(連結串列的逆序輸出)
阿新 • • 發佈:2019-01-28
目錄
題目描述
輸入一個連結串列,按連結串列值從尾到頭的順序返回一個ArrayList。
解法一:使用棧
單向連結串列的逆序輸出,我們可以很容易的想到使用一個棧作為輔助,棧的先進後出的特效能幫到我們大忙。(所以基礎的資料結構是真的很重要)
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; import java.util.Stack; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> result = new ArrayList<>(); if(listNode == null)return result; Stack<Integer> stack = new Stack<>(); while(listNode != null){ stack.push(listNode.val); listNode = listNode.next; } while(!stack.empty()){ result.add(stack.pop()); } return result; } }
解法二:遞迴
從連結串列首節點開始進行遞迴,直到尾部為止,每次遞迴時都將當前結點的值加入列表中。隨著遞迴過程,結點值會逆序加入到列表中。
import java.util.ArrayList; public class Solution { ArrayList<Integer> result = new ArrayList<>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode == null)return result; if(listNode != null){ //遞迴 printListFromTailToHead(listNode.next); //當遞迴進行到尾結點時,才會執行將當前結點的值加入到列表中的操作 result.add(listNode.val); } return result; } }
解法三:將原連結串列逆轉
這種方法想達到的目的是將原連結串列每個結點的next指標都指向前一個結點。所以需要兩個變數next和pre分別記錄當前節點的下一個結點和當前節點的上一個結點,然後將當前結點的next指標指向pre,並將pre和當前節點指標都向後移位,繼續下一個結點的處理。處理完整個連結串列之後,遍歷連結串列並將節點的值放入列表中
import java.util.ArrayList; public class Solution { ArrayList<Integer> result = new ArrayList<>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode==null)return result; ListNode pre = null; //記錄上一個結點,初始值為null,頭結點的上一個結點即為null ListNode next = null; //記錄下一個結點,便於後面的遍歷 //遍歷連結串列 while(listNode!=null){ next = listNode.next; //記錄下一個結點 listNode.next = pre; //當前節點的next指標指向pre pre = listNode; //pre指標和listNode指標都向後移位,繼續下個節點的處理 listNode = next; } //遍歷逆序完畢的節點,將每個節點的值放入result中 while(pre!=null){ result.add(pre.val); pre = pre.next; } return result; } }