思路
解法1:适用于数字不多的
1.把节点的数,都放进一个arraylist中
2.调用Collections.reverse(list)方法,将list转置
3.再遍历list,逐个放入数字
代码
解法1
import java.util.ArrayList;
import java.util.Collections;public class Main {public static void main(String[] args) {}public static class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) { this.val = val; }ListNode(int val, ListNode next) { this.val = val; this.next = next; }}static class Solution {public ListNode reverseList(ListNode head) {ListNode cur = head;ArrayList<Integer> list = new ArrayList<>();while (cur != null) {list.add(cur.val);cur=cur.next;}Collections.reverse(list);cur=head;for (int i = 0; i <= list.size() - 1; i++) {cur.val=list.get(i);cur=cur.next;}return head;}
}