定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
思考题:

  • 请同时实现迭代版本和递归版本。

    数据范围

    链表长度 [0,30][0,30]。

    样例

    输入:1->2->3->4->5->NULL 输出:5->4->3->2->1->NULL

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

递归

  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. ListNode tail = reverseList(head.next);
  13. head.next.next = head;
  14. head.next = null;
  15. return tail;
  16. }
  17. }