一、题目内容

image.png

二、题解

解法1:

思路

要求空间复杂度O(1),空间复杂度O(n),所以只能递归或者尾插遍历
pre,curr,next

代码

  1. //尾插遍历
  2. public class Solution {
  3. public ListNode ReverseList(ListNode head) {
  4. ListNode pre = null;
  5. ListNode curr = head;
  6. while(curr!=null){
  7. ListNode next = curr.next;
  8. curr.next = pre;
  9. pre = curr;
  10. curr = next;
  11. }
  12. return pre;
  13. }
  14. }
  15. //递归
  16. public class Solution {
  17. public ListNode ReverseList(ListNode head) {
  18. if(head == null||head.next==null){
  19. return head;
  20. }
  21. ListNode newHead = ReverseList(head.next);
  22. head.next.next = head;
  23. head.next = null;
  24. return newHead;
  25. }
  26. }