Remove Nth Node From End of List
/***Definitionforsingly-linkedlist.*structListNode{*intval;*ListNode*next;*ListNode(intx):val(x),next(NULL){}*};*/classSolution{public:voidrun(ListNode*head,int&num)//遍历链表,得到链表的长度;{while(head!=NULL){num++;head=head->next;}}ListNode*removeNthFromEnd(ListNode*head,intn){intnum=0;if(head==NULL)returnNULL;run(head,num);if(n>num)cout<<"删除位置不合法";else{ListNode*p=NULL,*q=NULL;inti=1;if(n==num)//删除首结点;{q=head;head=head->next;deleteq;}else//删除的不是首结点{q=head->next;p=head;while(i<num-n){p=q;q=q->next;i++;}p->next=q->next;deleteq;}returnhead;}}};
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。