LeetCode 19. Remove Nth Node From End of List
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Follow up: Could you do this in one pass?
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
实现思路:
要剔除倒数第K个链表结点,于是可以进行统计链表总结点个数N,然后删除第N-K个结点即可。
AC代码:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* temp=head;
int allNum=0;//统计所有结点的个数
while(temp!=NULL) {
allNum++;
temp=temp->next;
}
if(n>allNum) {
return head;
} else if(n==allNum) {
head=head->next;
return head;
} else {
int bgPos=allNum-n,cnt=0;//开始删除结点的位置
temp=head;
while(temp!=NULL) {
cnt++;
if(cnt==bgPos) {
if(temp->next!=NULL) {
temp->next=temp->next->next;
} else temp->next=NULL;
break;
}
temp=temp->next;
}
}
return head;
}
};