题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <cstddef>
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) { //思路是用两个指针,先让两个指针之间的距离为n,再同时移动到表尾,则left指向倒数第n个节点,删除它即可
// write code here
ListNode* left=head;
ListNode* right=head;
if (head->next==NULL) { //仅有一个节点
return head=nullptr;
}
for (int i=0; i<n; i++) {
right=right->next;
}
if (right==NULL) { //删除头结点情况
return head=head->next;
}
while (right->next!=NULL) {
right=right->next;
left=left->next;
}
left->next=left->next->next;
return head;
}
};
查看4道真题和解析