题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
ListNode *fast, *slow, *prev,*cur,*next;
int length = 0, i=0;
slow = head;
while(slow){
length++;
slow = slow->next;
}
if(length==n) return head->next;
prev = nullptr;
cur = head;
next = head->next;
slow = head;
while(i++!=length-n){
prev = cur;
cur = next;
next = next->next;
}
if(prev&&prev->next) prev->next = next;
return head;
}
};
查看10道真题和解析