首页 > 每天刷一道牛客题霸-第12天-删除链表的倒数第n个节点
头像
牛客652244724号
编辑于 2020-12-15 10:30
+ 关注

每天刷一道牛客题霸-第12天-删除链表的倒数第n个节点

题目

https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6?tpId=188&&tqId=36726&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking

import java.util.*;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */
public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        int count = 0;
        ListNode root = head;
        while(root!=null){
            count++;
            root = root.next;
        }
        int index = count - n + 1;
        root = head;
        if(index != 1){
            while(root != null&& index<=count){
                index--;
                if(index == 1){
                    root.next = root.next.next;
                    break;
                }
                root = root.next;
            }
            return head;
        }else{
            return head.next;
        }
    }
}

全部评论

(0) 回帖
加载中...
话题 回帖

相关热帖

近期精华帖

热门推荐