LeetCode——删除链表的倒数第N个节点

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

示例:


说明:

给定的 n 保证是有效的。

进阶:

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


不能

扫描二维码关注公众号,回复: 2178318 查看本文章

两趟扫描,第一趟,求出链表总节点数;第二趟,判断输入n是否有效,计算倒数第n个节点对应的序数,删除

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head == NULL) return head;
        int count = 0, newCount = 0;
        ListNode * node = head;
        while(node != NULL)
        {
            count++;
            node = node->next;
        }
        if(n<=0 || n>count) return head;
        if(n == count)
            return head->next;
        newCount = 1;
        node = head;
        while(newCount < count-n)
        {
            newCount++;
            node = node->next;
        }
        node->next = node->next->next;
        return head;       
    }
};


猜你喜欢

转载自blog.csdn.net/eartha1995/article/details/81007535