class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
if(n<=0) return NULL;
ListNode *dummynode = new ListNode(0);
dummynode->next = head;
ListNode *preDelete = dummynode;
for(int i=0;i<n;i++){
if(head == NULL) return NULL; //节点个数必须大于n
head = head->next;
}
while (head != NULL) {
head = head->next;
preDelete = preDelete->next;
}
preDelete->next = preDelete->next->next;
return dummynode->next;
}
};
思想是倒数第n个节点的确定是通过,两个指针(head和preDelete)之间距离为n(通过设置head,使head指针前进n个节点),所以当head指针指向最后一个节点时,preDelete指针指向的为倒数第n个节点,然后再利用preDelete->next = preDelete->next->next; 删除preDelete所指的节点。
删除链表中倒数第n个节点
最新推荐文章于 2021-09-15 11:47:14 发布