标签:rmi node 依次 nod div nbsp print color ext
1.头插法,在原地遍历
//先利用两个pre和next两个指针将头节点为cur的链表反转, //在依次遍历链表存储到一个ArrayList并返回 import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode cur) { ArrayList<Integer> list=new ArrayList<Integer>(); ListNode pre=null; ListNode next=null; while(cur!=null){ next=cur.next; cur.next=pre; pre=cur; cur=next; } while(pre!=null){ list.add(pre.val); pre=pre.next; } return list; } }
链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035 来源:牛客网 public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList list=new ArrayList(); if(listNode==null) return list; ListNode dummy=new ListNode(0); dummy.next=listNode; ListNode cur=listNode; // 链表就地反转 while(cur.next!=null) { ListNode temp=cur.next; cur.next=temp.next; temp.next=dummy.next; dummy.next=temp; } ListNode head=dummy.next; while(head!=null) { list.add(head.val); head=head.next; } return list; } }
标签:rmi node 依次 nod div nbsp print color ext
原文地址:https://www.cnblogs.com/Roni-i/p/10363153.html