6 逆序输出链表

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

 

解法一

使用栈。逆序输出和先入后出的结果一样,把链表的节点依次入栈再出栈即可。

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> list = new ArrayList<>();
        while (listNode!=null){
            stack.add(listNode.val);
            listNode = listNode.next;
        }

        while (!stack.isEmpty()){
            list.add(stack.pop());
        }
        
        return list;
        
    }
}

解法二 

  头插法重新建立链表。这种方法的好处是节省了空间,不需要额外的栈空间的开销。

  遍历原始链表,对每一个节点用头插的方式放到新的链表里。具体的在循环的过程中,先用一个temp节点保存正在修改节点的后续节点,这样正在修改的节点就可以放心大胆的改变其next。  

 public ArrayList<Integer> printListFromTailToHead(ListNode listNode){
        ListNode head = new ListNode(-1);
        ListNode temp;

        while (listNode != null){
            temp = listNode.next;

            listNode.next = head.next;
            head.next = listNode;

            listNode = temp;
        }

        ArrayList<Integer> list = new ArrayList<>();

        head = head.next;
        while (head!=null){
            list.add(head.val);
            head = head.next;
        }

        return list;

    }

 

posted @ 2019-02-19 17:00  AshOfTime  阅读(186)  评论(0编辑  收藏  举报