容易 删除链表中倒数第n个节点
37%
通过
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
注意
链表中的节点个数大于等于n
样例
给出链表1->2->3->4->5->null和 n = 2.
删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
挑战
O(n)时间复杂度
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
int length(ListNode *head) {
ListNode *p = head;
int l=0;
while(p != NULL) {
p = p->next;
l++;
}
return l;
}
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
int length = this->length(head);
if(length==0) {
return NULL;
}
if(length ==n){
return head->next;
}
n = length-n;
ListNode *p = head;
ListNode *q =head;
int i = 0;
while (q != NULL && i < n) {
q=p;
p=p->next;
i++;
}
q->next = p->next;
delete p;
return head;
}
};