LeetCode 19

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int count=0;
        ListNode* t=head;
        while(t)
        {
            count++;
            t=t->next;
        }
        n=count+1-n;
        //删掉正数第n个元素
        if(n==1)
        {
            head=head->next;
            return head;
        }
        n--;
        t=head;
        for(int i=1;i<n;i++)
        {
            t=t->next;
        }
        t->next=(t->next)->next;
        return head;
    }
};

你可能感兴趣的:(LeetCode面试经典,leetcode,算法,职场和发展)