[剑指offer刷题] AcWing 35. 反转链表 (简单、双指针、递归)

  • Post author:
  • Post category:其他




题型:双指针、递归

  1. 可以用双指针来写,这个比较容易想,也比较简单
  2. 也可以用递归的方式去解决,注意递归编程的思考方式



题目

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

思考题:

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

样例

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

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



java代码

递归解法

/**
 * 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 || head.next == null) return head;

        ListNode tail = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return tail;
    }
}

迭代解法

/**
 * 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 || head.next == null) return head;

        ListNode pre = head, q = head.next;
        while (q != null) {
            ListNode t = q.next;
            q.next = pre;
            pre = q;
            q = t;
        }

        head.next = null;
        return pre;
    }
}



版权声明:本文为qq_22473333原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。