代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseList(ListNode head) { if(head == null) return head; Stack<Integer> stack = new Stack<>(); ListNode cur = head; while(cur != null ) { stack.push(cur.val); cur = cur.next; } cur = head; while(! stack.isEmpty() ) { cur.val = stack.pop(); cur = cur.next; } return head; }}
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseList(ListNode head) { if(head == null) return head; ListNode pre = null; ListNode cur = head; ListNode next = null; while(cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; }}