Leecode 206. 反转链表

题目

反转一个单链表。

示例:

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

进阶:

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

解答

解法一:头插法

具体流程:

  1. 创建一个虚拟头节点,这样就不需要对头节点特殊处理了。
  2. 遍历原链表,将当前被遍历的结点按照头插法方式插入以虚拟头为首的链表中。
代码
/**
 * 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 dummy = new ListNode(0);
        ListNode pre = dummy;
        while(head != null) {
            ListNode next = head.next;
            head.next = pre.next;
            pre.next = head;
            head = next;
        }
        
        return dummy.next;
    }
}
结果

在这里插入图片描述

解法二:迭代法

注意处理好 pre,p 的关系就好了。

具体可看 《剑指Offer》

代码
/**
 * 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 pre = null;
        while(head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        
        return pre;
    }
}
结果

在这里插入图片描述

解法三:递归法

reverseList 方法的宏观语义:翻转 head 为头的链表,并返回新的头结点。

  1. 如果当前结点是 null ,或者没有下一个结点了,直接返回当前结点。
  2. 否则递归当前结点的 next 。
  3. 然后将当前结点链接到新链表的结尾。
  4. 最后返回新链表的头结点。
代码
/**
 * 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 newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        
        return newHead;
    }
}
结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值