206#反转链表

题目描述

206#反转链表

反转一个单链表。

示例:

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

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?


这是一个经典题目,《算法》第四版有它的原题,在中文版第103页1.3.30。

分析

这一题有两种方法来做:递归法和迭代法。

递归法

思路

假设整个链表有N个节点,要将整个链表反转,可以先将除第一个元素外的剩下N-1个元素先反转,再把第一个元素插入到剩下链表的末尾。再将问题往下细分,直到遇到空节点。要注意到异常情况(链表为空或只有一个或两个节点)。

源码

/**
 * 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)   return null;
        if (head.next == null)  return head;
        ListNode second = head.next;
        ListNode rest = reverseList(second);
        second.next = head;
        head.next = null;
        return rest;
    }
}

迭代法

思路

我们需要设置三个节点,first,second,reverse。在每轮迭代中,我们从原链表中提取节点first并将它插入到逆链表的开头。我们需要一直保持first指向原链表中所有剩余节点的首节点,second指向原链表中所有剩余节点的第二个节点,reverse指向结果链表的首节点。

源码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode first = head;
        ListNode reverse = null;
        while (first != null)
        {
            ListNode second = first.next;
            first.next = reverse;
            reverse = first;
            first = second;
        }
        return reverse;
    }
}
posted @ 2018-09-07 15:51  yuzhenzero  阅读(199)  评论(0编辑  收藏  举报