[LeetCode]Remove Nth Node From End of List

来源:互联网 发布:软件测试28原则 编辑:程序博客网 时间:2024/06/07 03:29

这里写图片描述

就是找到要删除的节点的前一个节点/** * 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) {        int sum =0;        ListNode* p = head;        while(p!=NULL){            ++sum;            p=p->next;        }        if(n==0)            return head;        if(n==sum)                return head->next;        ListNode* q;        q->next= head;        int j= 0;   //指向要去的前一个节点        while(j!=sum-n){            q = q->next;            ++j;        }        q->next = q->next->next;        return head;    }};
0 0