Skip to main content

链表内指定区间反转

·159 words·1 min
WFUing
Author
WFUing
A graduate who loves coding.
Table of Contents

  • 链接:https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

难点
#

链表的题目很早刷过,现在有些生疏了,再回顾一遍。

代码
#

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        //设置虚拟头节点
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next =head;
        ListNode pre = dummyNode;
        for(int i=0;i<m-1;i++){
            pre = pre.next;
        }
        ListNode cur = pre.next;
        ListNode Cur_next ;
        for(int i=0;i<n-m;i++){
            Cur_next = cur.next;
            cur.next = Cur_next.next;
            Cur_next.next = pre.next;
            pre.next = Cur_next ;
        }
        return dummyNode.next;
    }
}

反转:

// 反转链表
ListNode reverse(ListNode head){
    if(head == null)
        return head;
    ListNode cur = head;
    ListNode node = null;
    while(cur != null){
        ListNode tail = cur.next;
        cur.next = node;
        node = cur;
        cur = tail;
    }
    return node;
}