Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
解题思路
用两个节点指针对整个链表进行遍历。其中,一个指针用于遍历整个链表的尾部,另一个指针指向整个链表倒数第K个节点的前一个节点。算法步骤如下:
- 初始化两个指针,并且都指向链表头部,计数器 count = 0
- 尾指针 tail 从头开始遍历,直到为NULL(链表尾部),count++,直到 count = n;当 count = n 时,第K-1个节点的指针 top 移动到下一个节点
- 假如链表总长度为n,那么删除头结点;否则,删除 top 指向的节点的下一个节点
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) {
ListNode *tail = head, *top = head;
int count = 0, total = 1;
while(tail->next != NULL) {
if(count == n) {
top = top->next;
}
else {
count++;
}
tail = tail->next;
}
if(total == n) {
head = head->next;
}
else{
tail = top->next;
top->next = tail->next;
}
return head;
}
};