本文主要是介绍19. Remove Nth Node From End of List(Leetcode每日一题-2020.10.18),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Constraints:
- The number of nodes in the list is sz.
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Example1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example2
Input: head = [1], n = 1
Output: []
Example3
Input: head = [1,2], n = 1
Output: [1]
Solution
双指针
/*** 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) {if(!head)return NULL;ListNode *fast = head;while(n){fast = fast->next;--n;}ListNode dummy;dummy.next = head;ListNode *slow = head;ListNode *prev = &dummy;while(fast){fast = fast->next;slow = slow->next;prev = prev->next;}prev->next = slow->next;return dummy.next;}
};
这篇关于19. Remove Nth Node From End of List(Leetcode每日一题-2020.10.18)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!