删除链表的倒数第 N 个结点
题目链接:删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
方法一:加一个节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> m;
ListNode* t = head;
while (t) {
if (m.count(t)) {
return t;
}
m.insert(t);
t = t->next;
}
return NULL;
}
};