Given a linked list, remove the nth node from the end of list and return its head.
For 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.
Try to do this in one pass.
思路:
利用快指针先走n步,找到倒数第n个节点
然后删除。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* removeNthFromEnd(ListNode* head, int n) { 14 ListNode* slow = head; 15 ListNode* fast = head; 16 for(;n > 0;--n) { 17 fast = fast->next; 18 } 19 //如果此时快指针走到头了,// 说明倒数第 n 个节点就是第一个节点 20 if (fast == nullptr) return head->next; 21 while(fast != nullptr && fast->next!=nullptr) { 22 fast = fast->next; 23 slow = slow->next; 24 } 25 slow->next = slow->next->next; 26 return head; 27 28 } 29 };