目录
题目
Reverse a singly linked list.
解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ArrayList<Integer> valList = new ArrayList<Integer>();
ListNode p = head; while (p != null){ valList.add(p.val); p = p.next; } ListNode newHead = new ListNode(0); ListNode q = newHead;
for(int k = valList.size()-1; k >= 0; k--){ q.val = valList.get(k); if(k == 0){ q.next = null; } else { q.next = new ListNode(0); } q = q.next; } return newHead; } }
|
注意事项
- 翻转链表。获取所有元素,倒序构建新链表。