leetcode【链表】-----19. Remove Nth Node From End of List(删除链表中倒数第N个节点)
1、题目描述

2、分析
要删除链表中倒数第N个节点,用常规思维,那么我们需要知道链表的长度,这样用长度减去N再加1得到target也就是需要删除的第target个节点。删除链表的节点需要知道删除的节点的前驱,所以在上一步的过程中可以不加1,这样的得到的就是前驱。还要考虑一种情况,如果删除的是头结点,那么我们就需要创建一个节点用来指向头结点,这个节点就是头结点的前驱。这种方法会遍历两次链表,第一次是计算长度,第二次是遍历找到第target个节点。
可以使用双指针的方法来遍历,pre和cur指针。首先cur指针先向前走N步,如果此时cur指向空,说明N为链表的长度,则需要移除的为首元素,那么此时我们返回head->next即可,如果cur存在,我们再继续往下走,此时pre指针也跟着走,直到cur为最后一个元素时停止,此时pre指向要移除元素的前一个元素,我们再修改指针跳过需要移除的元素即可。来自(http://www.cnblogs.com/grandyang/p/4606920.html)。
3、代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head->next) return NULL;
ListNode* temp=head;
ListNode* Pos=(ListNode* )malloc(sizeof(ListNode));
Pos->next=head;
int len=0;
while(temp!=NULL){
len++;
temp=temp->next;
}
int target=len-n;
temp=Pos;
for(int i=0;i<target;++i){
temp=temp->next;
}
ListNode* temp2=temp->next;
temp->next=temp2->next;
//delete temp; //加上这句就报错,没明白。
return Pos->next;
}
};
//双指针
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head->next) return NULL;
ListNode *pre = head, *cur = head;
for (int i = 0; i < n; ++i) cur = cur->next;
if (!cur) return head->next;
while (cur->next) {
cur = cur->next;
pre = pre->next;
}
pre->next = pre->next->next;
return head;
}
};
4、相关知识点
链表的基本知识,基本操作,学会转换。

浙公网安备 33010602011771号