leetcode-链表-19.删除链表的倒数第N个节点

class Solution 
{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) 
{
        int count=0;//存放链表长度
        ListNode *p=head;
        while(p)//计算链表长度
        {
            count++;
            p=p->next;
        }
        p=head;
        if(count==1) return {};//链表只有一个元素
        else if(count-n==0) return head->next;//要删除的元素是第一个
        else 
        {
            for(int i=1;i<count-n;i++)
            {
                p=p->next;
            }
            p->next=p->next->next;
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32391345/article/details/106819143