算法-第四版-练习1.3.30解答

题目

编写一个函数,接受一条链表的首结点作为参数,(破坏性地)将链表反转并返回结果链表的首结点。

思路

搬运。书上有具体的思路。

代码

方法一(迭代)

public Node reverse(Node x)
    {
        Node first = x;
        Node reverse = null;
        while (first != null)
        {
            Node second = first.next;
            first.next = reverse;
            reverse = first;
            first = second;
        }
        return reverse;
    }

方法二(递归)

public Node reverse(Node first)
    {
        if (first == null) return null;
        if (first.next == null) return first;
        Node second = first.next;
        Node rest = reverse3(second);
        second.next = first;
        first.next = null;
        return rest;
    }

猜你喜欢

转载自blog.csdn.net/qq_26207065/article/details/81478541