题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
双指针,没什么好说的
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if(!head) return head;
ListNode* fast = head;
ListNode* slow = head;
for(int i = 0; i < n && head; ++i) { fast = fast->next; }
if(!fast) return head->next;
while(fast->next) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};

莉莉丝游戏公司福利 614人发布

查看30道真题和解析