反转链表(中等难度)(第92题)

题目:

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

分析一:

递归:看了几个大佬的解释,还是不是很明白,准备一周后再来复习。先上代码吧。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    ListNode nextNode = null;
    public ListNode reverse(ListNode head, int n) {
        if (n == 1) {
            nextNode = head.next;
            return head;
        }
        ListNode last = reverse(head.next, n - 1);
        head.next.next = head;
        head.next = nextNode;
        return last;
    }
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == 1) {
            return reverse(head, n);
        }
        head.next = reverseBetween(head.next, m - 1, n - 1);
        return head;
    }
}

分析二:

迭代:这个方法就是多用指针,疯狂指,考虑好边界条件。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode first = dummy;
        ListNode second = dummy.next;
        while (m > 1) {
            first = second;
            second = second.next;
            m--;
            n--;
        }
        ListNode con = first;
        ListNode tail = second;
        ListNode third = null;
        while (n > 0) {
            third = second.next;
            second.next = first;
            first = second;
            second = third;
            n--;
        }
        if (con != null) {
            con.next = first;
        } else {
            dummy.next = first;
        }
        tail.next = second;
        return dummy.next;

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值