(链表 双指针)leetcode 19. Remove Nth Node From End of List

mac2022-06-30  89

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.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

 

-------------------------------------------------------------------------------------------------------------------------

这个题就是移去从表尾开始的第n 个元素。emmmm,这个最好画图,便于理解。

可以用双指针。

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 *s = head; ListNode *e = head; if(!head) return NULL; for(int i = 0; i < n; i++) e = e->next; if(!e) return head->next; while(e->next){ s = s->next; e = e->next; } s->next = s->next->next; return head; } };

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10704307.html

最新回复(0)