image.png
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. ListNode node =head;
  12. ListNode newHead=null;
  13. while(node!=null){
  14. ListNode tmp=node.next;
  15. node.next=newHead;
  16. newHead=node;
  17. node=tmp;
  18. }
  19. return newHead;
  20. }
  21. }

方法二:递归法

  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||head.next==null) return head;
  12. else{
  13. ListNode newHead=reverseList(head.next);
  14. head.next.next=head;
  15. head.next=null;
  16. return newHead;
  17. }
  18. }
  19. }