Create 19. Remove Nth Node From End of List.md

This commit is contained in:
唐树森 2018-12-18 16:07:26 +08:00 committed by GitHub
parent a88f6e6713
commit 2ecb3669d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,40 @@
# [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
# 思路
题意就是去掉链表中倒数第n个节点。
涉及到链表中倒数节点的思路都是使用两个指针p1、p2两个指针初始都是headp2先走n步然后p1、p2再同时走直到p2到达链尾
此时p1就位于链表倒数第n个节点的前一个节点。
需要注意当要删除的节点就是head时需要特殊处理。
时间复杂度O(N)空间复杂度O(1)
# C++
``` C++
/**
* 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) {
if(n <= 0) return head;
ListNode *p1 = head, *p2 = head;
while(n--) p2 = p2 -> next; // p2先走n步
if(p2 == NULL){ // 此时删掉的应该是head
head = head -> next;
delete p1;
return head;
}
while(p2 -> next){
p1 = p1 -> next;
p2 = p2 -> next;
} // 此时p1位于倒数第n个节点的前一个节点
p2 = p1 -> next;
p1 -> next = p2 -> next;
delete p2;
return head;
}
};
```