LeetCode 19. Remove Nth Node From End of List

题目

c++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        
        ListNode* term = head;
        ListNode* temp;
        int num=0;
        while(term!=NULL)
        {
            term=term->next;
            num++;
        }
        
        if(num==0||n==0)
            return head;
        temp = head;
        term = head;
        int pos = num-n;
        int i=0;
        while(term!=NULL)
        {
            if(pos==i)
            {
                if(i==0)
                {
                    head=term->next;
                    break;
                }
                else
                {
                    temp->next = term->next;
                    break;
                }
            }
            else
            {
                
                temp = term;

                term=term->next;
                i++;
            }
        }
        return head;
        
    }
};
原文地址:https://www.cnblogs.com/dacc123/p/11109069.html