Leetcode 19.Remove Nth Node From End of List

题目链接:19. Remove Nth Node From End of List

  删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int len = 0;
        ListNode newhead = new ListNode(0);
        newhead.next = head;
        ListNode p = newhead;
        while (null != p) {
            len += 1;
            p = p.next;
        }
        p = newhead;
        int cnt = len - n - 1 ;
        while (cnt != 0) {
            p = p.next;
            cnt--;
        }
        p.next = p.next.next;
        return newhead.next;
    }
}
打赏

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.