标签:++ leetcode code cpp remove 删除 开始 mat ret
删除链表的倒数第\(n\)个结点,返回链表的头结点。
len - n
个元素。时间复杂度:\(O(n)\)。class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = 0;
ListNode *t = head;
while(t != NULL) { ++len; t = t -> next; }
ListNode res(0);
res.next = head;
t = &res;
for(int i = 0; i < len - n; ++i)
t = t -> next;
t -> next = t -> next -> next;
return res.next;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode res(0);
res.next = head;
ListNode *fast = &res, *slow = &res;
while(fast -> next)
{
if(n)
--n;
else
slow = slow -> next;
fast = fast -> next;
}
slow -> next = slow -> next -> next;
return res.next;
}
};
好多“思维”题都要用到双指针的思想呢。
标签:++ leetcode code cpp remove 删除 开始 mat ret
原文地址:https://www.cnblogs.com/songjy11611/p/12332913.html