6. 从尾到头打印链表[java]

题目描述 在线编程

从尾到头反过来打印出每个结点的值

题解

头插法可将链表反转

/**
*    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> ret=new ArrayList<>();
       ListNode dummy=new ListNode(-1);
       ListNode cur=listNode;
        while(cur!=null){
            ListNode next=cur.next;
            cur.next=dummy.next;
            dummy.next=cur;
            
            cur=next;
        }
        cur=dummy.next;
        while(cur!=null){
           ret.add(cur.val);
            cur=cur.next;
        }
        return ret;
    }
}

猜你喜欢

转载自www.cnblogs.com/zslhg903/p/11203295.html
今日推荐