【力扣】92. 反转链表 II

一、题目描述:

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

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

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题思路:

在这里插入图片描述

三、代码描述:

/**
 * 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||head.next==null||m==n){
           return head;
       }
       ListNode newHead=new ListNode(-1);
       newHead.next=head;
       ListNode first=newHead;
       //first为第(m-1)个节点
       for(int i=1;i<m;i++){
           first=first.next;
       }
       //second为链表反转之后的最后一个节点
       //注意:一定要保存Second节点,在后面首尾相接时会用到。
       ListNode second=first.next;
       //l为链表反转之后的第一个节点
       ListNode l=second;
       //third为第(n+1)个节点
       ListNode third=l.next;
       //反转链表
       for(int i=m;i<n;i++){
           ListNode next=third.next;
           third.next=l;
           l=third;
           third=next;
       }
       //将(m-1)个节点的next指向反转之后的头结点
       first.next=l;
       //将反转之后的最后一个节点的next指向(n+1)个节点
       second.next=third;
       return newHead.next;
    }
}
发布了75 篇原创文章 · 获赞 14 · 访问量 1891

猜你喜欢

转载自blog.csdn.net/qq_45328505/article/details/104870231