从尾到头打印链表

题目 从尾到头打印链表

image-c61511d6

思路分析

代码实现

单链表只能从前往后遍历,先从前往后遍历一遍输入的链表,将结果记录在答案数组中。

最后再将得到的数组逆序即可。

 /**

 * Definition for singly-linked list.

 * class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) { val = x; }

 * }

 */

class Solution {

    public int[] printListReversingly(ListNode head) {

        int[] x=new int[1010];

        int idx=0;

        while(head!=null){

            x[idx++]=head.val;

            head=head.next;

        }

        int[] res=new int[idx];

        for(int i=0,j=idx-1;i<idx;i++,j--)

            res[i]=x[j];

        return res;

    }

}

利用栈特性

/**

 * Definition for singly-linked list.

 * class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) { val = x; }

 * }

 */

class Solution {

    public int[] printListReversingly(ListNode head) {

        Stack<Integer> stk=new Stack<>();

        for(ListNode p=head;p!=null;p=p.next)   stk.push(p.val);

        int[] res=new int[stk.size()];

        int k=0;

        while(!stk.empty()) res[k++]=stk.pop();

        return res;

    }

}

同类题型

视频讲解


项目分区导航三元组排序 ⬅️ | 02-从尾到头打印链表 | ➡️ 删除链表中重复的节点