【leetcode19】删除链表的倒数第N个节点 Java题解

leetcode分类下所有的题解均为作者本人经过权衡后挑选出的题解,在易读和可维护性上有优势

每题只有一个答案,避免掉了太繁琐的以及不实用的方案,所以不一定是最优解

给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head.next == null) return null;
        ListNode p1 = head, p2 = head;
        int i = 0;
        while(p1.next != null){
            p1 = p1.next;
            i++;
            if(i > n)
                p2 = p2.next;
        }
        if(i == n - 1)
            head = head.next;
        else
            p2.next = p2.next.next;
        return head;
    }
}

 思路:

  • i == n - 1 是当head只有一个值的情况

猜你喜欢

转载自blog.csdn.net/weixin_43046082/article/details/89044152