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

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

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

import java.util.*;

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

public class Solution {
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        // 反转
        head = reverse(head);
        // 删除
        ListNode temp = head;
        while (n > 2) {
            head = head.next;
            n--;
        }
        if (n == 1) return reverse(head.next);
        head.next = head.next.next;
        // 反转
        return reverse(temp);
    }

    public ListNode reverse(ListNode head) {
        if (head == null) return null;
        ListNode pre = null;
        ListNode cur = null;
        while (head != null) {
            cur = head.next;
            head.next = pre;
            pre = head;
            head = cur;
        }
        return pre;
    }
}

全部评论

相关推荐

08-21 16:35
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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