822. 相反的順序存儲
給出一個鏈表,並將鏈表的值以倒序存儲到數組中。
樣例
樣例1
輸入: 1 -> 2 -> 3 -> null
輸出: [3,2,1]
樣例2
輸入: 4 -> 2 -> 1 -> null
輸出: [1,2,4]
代碼區:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* username:softstarhhy
* @param head: the given linked list
* @return: the array that store the values in reverse order
*/
public List<Integer> reverseStore(ListNode head) {
// write your code here
//採用頭插法
List<Integer> list=new ArrayList<Integer>();
ListNode q=head;
if(head==null)
return list;
ListNode p=head.next;
ListNode mid=p.next;
if(p==null)
return list;
while(p!=null)
{
if(p!=null)
{
mid=p.next;//後繼指針
q.next=p.next;//前置元素獲得後繼指針 q實際爲最末尾元素
p.next=head;//後繼指針指向前置元素
head=p;//重置head
p=mid;//開始下次遍歷
}
}
while(head!=null)
{
list.add(head.val);
head=head.next;
}
return list;
}
}