题解 | #删除链表的倒数第n个节点#

删除链表的倒数第n个节点

https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param n int整型
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
         ListNode newHead = new ListNode(-1);
        ListNode tail = head;
        newHead.next = head;
        ListNode pre = newHead;
        while (n != 1) {
            tail = tail.next;
            n--;
        }
        ListNode cur = head;
        while (tail.next != null) {
            cur = cur.next;
            pre = pre.next;
            tail = tail.next;
        }
        pre.next = cur.next;
        cur.next = null;
        return newHead.next;
    }
}

全部评论

相关推荐

码农索隆:想看offer细节
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务