每日一道算法题--leetcode 19--删除链表的倒数第N个结点--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* previous=new ListNode(1);
        ListNode* current=head;
        int length=1;
        if(head!=NULL){  
        while(current->next!=NULL){
            length++;
            current=current->next;
        }
        }
        int num=length-n+1;
        current=head;
        if(num==1){
            head=head->next;
        }
        while(num>1){
            if(current->next!=NULL){
                previous=current;
                current=current->next;
            }
            num--;
        }
        previous->next=current->next;
        
       
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/transformed/article/details/84067522