19. Remove Nth Node From End of List C++删除链表的倒数第N个节点

时间:2023-03-09 01:11:26
19. Remove Nth Node From End of List C++删除链表的倒数第N个节点

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

使用双指针法,可以仅遍历一次完成节点的定位

/**
* 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* l = new ListNode();
l = head;
ListNode* r = new ListNode();
r = l;
while(n--)
r = r->next;
//用于判断head是否为单节点链表
if(r == NULL)
return head->next;
while(r != NULL && r->next != NULL)
{
r = r->next;
l = l->next;
}
ListNode* temp = new ListNode();
temp = l->next;
l->next = l->next->next;
if(temp)
delete(temp);
return head;
}
};