leetCode 19. Remove Nth Node From End of List 链表
19. Remove Nth Node From End of List
Given a linked list, remove thenthnode from the end of list and return its head.
For example,
Givenlinkedlist:1->2->3->4->5,andn=2.Afterremovingthesecondnodefromtheend,thelinkedlistbecomes1->2->3->5.
Note:
Givennwill always be valid.
Try to do this in one pass.
题目大意:
找到链表中倒数第N个元素,删除这个元素。
代码如下:
/***Definitionforsingly-linkedlist.*structListNode{*intval;*ListNode*next;*ListNode(intx):val(x),next(NULL){}*};*/classSolution{public:intlengthOfList(ListNode*head){inti=0;while(head!=NULL){i++;head=head->next;}returni;}ListNode*removeNthFromEnd(ListNode*head,intn){if(head==NULL)returnNULL;ListNode*p=head;intpre=lengthOfList(head)-n;if(pre==0)returnhead->next;cout<<pre<<""<<lengthOfList(head)<<endl;while(--pre)p=p->next;p->next=p->next->next;returnhead;}};
2016-08-12 14:02:00
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。