給定一個鏈表,刪除鏈表中倒數(shù)第n個節(jié)點,返回鏈表的頭節(jié)點笆檀。
注意事項
鏈表中的節(jié)點個數(shù)大于等于n
您在真實的面試中是否遇到過這個題?
Yes
樣例
給出鏈表1->2->3->4->5->null和 n = 2.
刪除倒數(shù)第二個節(jié)點之后盒至,這個鏈表將變成1->2->3->5->null.
/**
* 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.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
if(head->next==NULL){
return NULL;
}
ListNode *p=head;
ListNode *q=head;
ListNode *temp;
for(int i=0;i<n;i++){
p=p->next;
}
if(p==NULL){
//要刪除的節(jié)點是頭節(jié)點
temp=head;
head=head->next;
free(temp);
return head;
}
ListNode * pre_q=q;
q=q->next;
p=p->next;
while(p!=NULL){
q=q->next;
p=p->next;
pre_q=pre_q->next;
}
pre_q->next=q->next;
free(q);
return head;
//return q;
}
};