題目描述
解題方法1
- 鏈表是鏈式存儲結構,不同於數組,沒有辦法直接逆序遍歷。
- 第一反應,我們可以藉助於棧或數組,先順序遍歷鏈表把所有元素存儲到數組或棧中,然後再遍歷數組或棧進行逆序打印。
- 空間複雜度爲n,時間複雜度爲n,不推薦。
public class Test {
public static void main(String[] args) throws Exception {
int[] arr = {10,20,30,40,50};
Node head = create(arr);
show(head);
}
public static void show(Node head){
if(head==null){
return;
}
Stack s = new Stack();
for(Node p =head.next;p!=null;p=p.next){
s.push(p.val);
}
while(!s.empty()){
System.out.print(s.pop() + " ");
}
}
public static Node create(int[] arr){
Node head = new Node(0);
Node newnode = null;
Node tail = head;
for(int a:arr){
newnode = new Node(a);
newnode.next = tail.next;
tail.next = newnode;
tail = newnode;
}
return head;
}
}
class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}
解題方法2
- 既然可以使用棧解決,那麼很自然想到可以使用遞歸來解決,對於每一層遞歸只打印第一個節點元素。
public class Test {
public static void main(String[] args) throws Exception {
int[] arr = {10,20,30,40,50};
Node head = create(arr);
show(head.next);
}
public static void show(Node head){
if(head==null){
return;
}
show(head.next);
System.out.println(head.val);
}
public static Node create(int[] arr){
Node head = new Node(0);
Node newnode = null;
Node tail = head;
for(int a:arr){
newnode = new Node(a);
newnode.next = tail.next;
tail.next = newnode;
tail = newnode;
}
return head;
}
}
class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}
解題方法3
- 我們也可以將鏈表反轉再順序打印,最後再將鏈表還原。
- 此方法時間複雜度也爲n,但是係數爲3。
public class Test {
public static void main(String[] args) throws Exception {
int[] arr = {10,20,30,40,50};
Node head = create(arr);
show(head);
}
public static void show(Node head){
reverse(head);
for(Node p=head.next;p!=null;p=p.next){
System.out.print(p.val+" ");
}
reverse(head);
}
public static Node reverse(Node head){
if(head==null || head.next==null){
return head;
}
Node p = head.next;
head.next = null;
while(p!=null){
Node temp = p.next;
p.next = head.next;
head.next = p;
p=temp;
}
return head;
}
public static Node create(int[] arr){
Node head = new Node(0);
Node newnode = null;
Node tail = head;
for(int a:arr){
newnode = new Node(a);
newnode.next = tail.next;
tail.next = newnode;
tail = newnode;
}
return head;
}
}
class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}