[LeedCode OJ]#19 Remove Nth Node From End of List

来源:互联网 发布:大非农数据利空金银 编辑:程序博客网 时间:2024/05/18 18:46

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:libin493073668@sina.com】


题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/


题意:

给出一个链表,要求删除倒数第n个节点


思路:

还是使用双指针法,让第一个指针领先第二个指针n-1的距离,当第一个指针到达了链表尾部的时候,那么第二个指针就是指向的倒数第n个结点了


/** * 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 *first = head;ListNode *second = head;ListNode *pre = nullptr;for(int i = 1; i<n; i++)first = first->next;while(first->next){pre = second;first = first->next;second = second->next;}if(pre==nullptr)head = second->next;elsepre->next = second->next;return head;}};


0 0
原创粉丝点击