问题描述:给定一个链表,删除链表中倒数第n个结点,返回链表的头结点 如给定1->2->3->4->5->NULL和2,返回1->2->3->5->NULL.
解题思路:这题与找到链表第n个元素差不多,就多了一步删除,设置两个指针,一个指针先走到指定位置,另一个与现在这个指针一起走,找到结点后,一个覆盖另一个即可
解题思路:class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
ListNode *dummy= new ListNode(0);
dummy->next=head;
head=dummy;
ListNode *one=head->next;
ListNode *two=head->next;
for(int i=0;i<n;i++){
one=one->next;
}
if(one==NULL){
return head->next->next;
}
while(one->next!=NULL){
one=one->next;
two=two->next;
}
two->next=two->next->next;
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
ListNode *dummy= new ListNode(0);
dummy->next=head;
head=dummy;
ListNode *one=head->next;
ListNode *two=head->next;
for(int i=0;i<n;i++){
one=one->next;
}
if(one==NULL){
return head->next->next;
}
while(one->next!=NULL){
one=one->next;
two=two->next;
}
two->next=two->next->next;
};
感悟:这个题就是找到倒数第n个元素与删除该结点两种算法的结合,思路很简单。