leetcode--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 {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null || head.next==null)
            return head;
        if(m!=1){
            ListNode temp=head.next;
            ListNode preFirst=head;//指向翻转处的前一个节点的值
            //两个指针移到反转处
            for(int i=0;i<m-2;i++){
                temp=temp.next;
                preFirst=preFirst.next;
            }
            //从temp处开始反转链表
            //由于temp是反转后的最后一个节点,记录temp这个节点
            ListNode last=temp;
            ListNode pre=temp;//在这开始反转链表
            ListNode pNode=temp.next;
            ListNode next=null;
            for(int i=0;i<n-m;i++){
                next=pNode.next;
                pNode.next=pre;
                pre=pNode;
                pNode=next;
            }
            //反转前面链接起来,后面链接起来pre是反转后的头结点
            preFirst.next=pre;
            last.next=pNode;
        }else{
            ListNode pre=head;
            ListNode pNode=head.next;
            ListNode next=null;
            ListNode last=head;//记录下last节点
            for(int i=0;i<n-m;i++){
                next=pNode.next;
                pNode.next=pre;
                pre=pNode;
                pNode=next;
            }
            last.next=pNode;//反转后最后一个节点链接上后续的节点
            return pre;//pre是反转后的头结点
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/u010651249/article/details/84325632
今日推荐