剑指offer6 从尾到头打印链表

如果没有要求,反转链表后顺序打印即可。O(n)。

/**
*    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) {
        if(listNode==null) return new ArrayList<>();
        
        ArrayList<Integer> ans = new ArrayList<>();
        ListNode pre=null;
        ListNode next;
        while(listNode!=null){
            next = listNode.next;
            listNode.next = pre;
            pre = listNode;
            listNode = next;
        }
        while(pre!=null){
            ans.add(pre.val);
            pre = pre.next;
        }
        return ans;
    }
}

如果要求不能修改原链表结构呢?

那就只能搞一个栈了。

 

/**
*    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) {
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> ans = new ArrayList<>();
        while(listNode!=null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.empty()){
            ans.add(stack.pop());
        }
        return ans;
    }
}

能用栈基本就能用递归:

/**
*    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> ans = new ArrayList<>();
        recursivePrint(listNode,ans);
        return ans;
    }
    private void recursivePrint(ListNode listNode,ArrayList<Integer> ans){
        if(listNode!=null){
            recursivePrint(listNode.next,ans);
            ans.add(listNode.val);
        }
    }
}

 

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        # 26ms 5860k
        #ans = []
        #p = listNode
        #while p is not None:
        #    ans.insert(0,p.val)
        #    p=p.next
        #return ans
        # 24ms 5744k
        if listNode is None:
            return []
        stack = []
        p = listNode
        while p is not None:
            stack.append(p.val)
            p=p.next
        return stack[::-1]

 

posted @ 2019-02-13 14:09  大胖子球花  阅读(130)  评论(0)    收藏  举报