美文网首页
算法-6.从尾到头打印链表

算法-6.从尾到头打印链表

作者: zzq_nene | 来源:发表于2020-08-08 22:32 被阅读0次

    从尾到头打印链表

    输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
    思路:首先需要对链表进行逆序
    然后再对将链表保存在数组中

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
        public int[] reversePrint(ListNode head) {
            ListNode pre = null;    
            ListNode cur = head;
            ListNode next = null;
    
            while (cur != null) {
                next = cur.next;
    
                cur.next = pre;
                pre = cur;
                cur = next;
    
            }
    
            ListNode reverseListNode = pre;
            ArrayList<Integer> list = new ArrayList<>();
            while (reverseListNode != null) {
                list.add(reverseListNode.val);
                reverseListNode = reverseListNode.next;
            }
            int[] array = new int[list.size()];
            for(int i=0;i<list.size();i++) {
                array[i] = list.get(i);
            }
            return array;
        }
    

    附:链表反转

        public static ListNode reverse(ListNode head) {
            ListNode pre = head;
            ListNode cur = head.next;
            ListNode next = null;
    
            head.next = null;
            while (cur != null) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
    
        public static ListNode reverse1(ListNode head) {
            ListNode pre = null;
            ListNode cur = head;
            ListNode next = null;
    
            // next = 2
            // pre = 0
            // cur = 1
            while (cur != null) {
                next = cur.next;
    
                cur.next = pre;
                pre = cur;
                cur = next;
    
            }
            return pre;
        }
    

    相关文章

      网友评论

          本文标题:算法-6.从尾到头打印链表

          本文链接:https://www.haomeiwen.com/subject/axlrrktx.html