题目链接:点击这里
题目给的链表不带空的头结点。为了方便对首结点进行操作,人为地设置一个空的头结点。
删除倒数第 个节点,也就是删除从列表开头数起的第 个结点,其中 是列表的长度。只要我们找到列表的长度 ,这个问题就很容易解决。
/**
* 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 *kong = new ListNode(-1); //设置一个空的头结点
kong->next = head;
ListNode *p = kong->next;
int len = 0; //获取链表长度
while(p)
{
len++;
p = p->next;
}
p = kong;
int i = 1;
while(i<len-n+1)
{
i++;
p = p->next;
}
p->next = p->next->next;
return kong->next;
}
};
让快指针先走 步,然后快慢指针开始同速前进。这样当快指针走到链表末尾 时,慢指针所在的位置就是倒数第 个链表节点。
/**
* 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 *kong = new ListNode(-1); //设置一个空的头结点
kong->next = head;
ListNode *slow = kong, *fast = kong;
for(int i = 1; i <= n + 1; i++)
fast = fast->next;
while(fast!=NULL)
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return kong->next;
}
};