欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LintCode1661. 删除链表中的第n到m个节点

程序员文章站 2022-07-12 11:58:51
...

描述

给定一个链表,删除链表中的第 n 到 m 个节点,返回链表的头节点。

编号从 00 开始

链表的长度不超过 100000100000

样例
样例 1:

输入:head = 1->2->3->4->5->null, n = 1, m = 2
输出:1->4->5->null
样例 2:

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

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: The first node of linked list
     * @param n: the start index
     * @param m: the end node
     * @return: A ListNode
     */
    public ListNode deleteNode(ListNode head, int n, int m) {
        // Write your code here
            ListNode nodeNc = head;
        if (n == 0) {
            int count = 0;
            while (head != null && count <= m) {
                head = head.next;
                count++;
            }
            return head;
        } else {
            int count1 = 0;
            while(head!=null && count1 < n-1){
                head = head.next;
                count1++;
            }
            int count2 = 0;
            ListNode nodem = nodeNc;
            while (head!= null && count2 <= m ){
                nodem = nodem.next;
                count2++;
            }
            head.next = nodem;
            return nodeNc;
  	  }
    }
}