/**
* 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* tmp=head;
int count=0;
while(tmp!=NULL){
count++;
tmp=tmp->next;
}
if(n==count)//如果要刪除的是頭結點
{
head=head->next;
return head;
}
tmp=head;
while(count>n+1){//否則找到節點,進行刪除
tmp=tmp->next;
count--;
}
tmp->next=tmp->next->next;
return head;
}
};
LintCode-劍指Offer-(174)刪除鏈表中倒數第n個節點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.