题目

image.png

代码

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. if(head == null) return head;
  12. Stack<Integer> stack = new Stack<>();
  13. ListNode cur = head;
  14. while(cur != null ) {
  15. stack.push(cur.val);
  16. cur = cur.next;
  17. }
  18. cur = head;
  19. while(! stack.isEmpty() ) {
  20. cur.val = stack.pop();
  21. cur = cur.next;
  22. }
  23. return head;
  24. }
  25. }
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. if(head == null) return head;
  12. ListNode pre = null;
  13. ListNode cur = head;
  14. ListNode next = null;
  15. while(cur != null) {
  16. next = cur.next;
  17. cur.next = pre;
  18. pre = cur;
  19. cur = next;
  20. }
  21. return pre;
  22. }
  23. }