劍指offer中經典的算法題之從頭到尾打印鏈表
阿新 • • 發佈:2018-09-23
人的 打印 pri 沒有 util 經典的 rom 先進後出 tlist
話不多說上代碼:
我自己的算法是:
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> returnList = new ArrayList<Integer>(); if(listNode == null){ return returnList; } ListNode re = reverse(listNode); while(re != null){ returnList.add(re.val); re = re.next; } return returnList; }public static ListNode reverse(ListNode listNode){ if(listNode.next == null){ return listNode; } ListNode next = listNode.next; listNode.next = null; ListNode re = reverse(next); next.next = listNode; return re; } }
這是我沒有參考其他人的答案自己想出來的簡單的算法,算是比較糟糕了,思路是先反轉鏈表,再進行打印
下面列出其他人比較經典的算法:
1. 利用棧,先進後出
2 . 遞歸
劍指offer中經典的算法題之從頭到尾打印鏈表