【算法】从尾到头打印链表

141 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

题目

输入一个链表头节点,从尾到头反过来打印每个节点值。

解题思路

从尾到头输出打印实际上就是对链表方向的改变。从头到尾输出打印链表是简单的,若要反制输出就需要根据要求来看如何具体实现了。

栈方法

使用Stack栈来存储链表内容,先从头到尾遍历一次链表。因为栈的特点是"后进先出",可以利用这一特点将链表结构内容进行倒置处理。当遍历完链表存储在栈中后,再从栈中输出每个节点这时候输出顺序就是从链表的尾部开始打印了。

      	ListNode head;
	Stack<ListNode> stack = new Stack<ListNode>(); //创建栈
        ListNode temp = head;
        while (temp != null) { // 循环链表 获取下一个
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size(); // 获取大小
        int[] print = new int[size];
        for (int i = 0; i < size; i++) { //栈后进先出特点  
            print[i] = stack.pop().val;
        }
        return print;

除了使用到Stack之外,若不允许采用现有数据结构的形式实现。可通过先获取链表长度,新建数组倒置存储数组数据来实现。

        ListNode temp = head;
        int i = 0;
        while(temp != null){ // 遍历链表结构获取长度
            i++;
            temp = temp.next;
        }
        int [] print = new int [i]; // 创建数组
        while(head != null){ // 倒置存储链表数据
            print[--i] = head.val;
            head = head.next;
        }
        return arr;

倒置链表法

倒置方法会破坏链表原有结构,在其基础上通过链表数据调换将首尾数据遍历交换处理。

        ListNode pre = null;
        ListNode next = null;
        int i = 0;

        while (head != null){ // 将链表数据倒置
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
            i++;
        }
      	// 后面的步骤是一样的
        int[] print = new int[i];
        i = 0;
        while(pre != null){ // 倒置存储链表数据
            print[i] = pre.val;
            pre = pre.next;
            i++;
        }
        return print;

递归法

使用递归函数遍历链表,然后讲所有数据添加到List中,最后在将数据塞入到数组打印。

ArrayList<Integer> tmp = new ArrayList<Integer>();
    void recur(ListNode head) {
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    }
    recur(head); // 递归遍历
    int [] print = new int [i]; // 创建数组
    for(int i =0; i< tmp.size();i++){
        print[i] = tmp.get(i);
    }