直观思维先走到底得出node数目count,再从前走count - N。很明显时间复杂度2n,这是最直白最普通的思维,没有联系计算机相关数据结构知识,所以效率差。之后看了解答用了双指针,让fast先走N步然后slow再同时走,那么fast到底时slow就是目标位置。这才是计算机式的解答。
本人AC版:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
if (n == 0)
return head;
int count = 0;
struct ListNode *node = head;
while ((node)) {
node = node->next;
count++;
}
node = head;
if (n == count) {
head = head->next;
free(node);
}
else {
for (int i = 0; i < count - n - 1; i++)
node = node->next;
struct ListNode *tmpnode = node->next;
node->next = node->next->next;
free(tmpnode);
}
return head;
}
解答nice版:
struct ListNode *fixed_removeNthFromEnd(struct ListNode *head, int n) {
ListNode dummy = {-1, head};
ListNode *xp = head, *yp = &dummy;
for (int i = 1; i < n; i++)
xp = xp->next;
while (xp->next) {
yp = yp->next;
xp = xp->next;
}
ListNode *tmpp = yp;
yp->next = yp->next->next;
free(tmpp->next);
return dummy.next;
}