暴力解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* p=head;
int num=1;
//统计链表总长度
while(p->next!=NULL)
{
p=p->next;
num++;
}
//倒数第n个即正数第num-n+1个
p=head;
//需要使p到待删除节点的前一个,即到第num-n个 又p当前已在第一个 所以循环num-n-1次
//但若num-n-1<=0,即要删除的是第一个
if (n==num)return head->next;
for(int i=1;i<num-n;i++)
{
p=p->next;
}
struct ListNode*q=p->next;
p->next=p->next->next;
free(q);
q=NULL;
p=NULL;
return head;
}
法2:快慢指针法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/* Description:
* 使用快慢指针的方法, 快指针比慢指针先跑n个节点,
*等快指针到头的时候,慢指针所指向的就是待删除的节点。
*/
typedef struct ListNode Node;
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
Node *fast = head;
Node *slow = head;
Node *last_slow = NULL;
int i=0;
/* fast pointer runs n steps first */
while(fast){
if(i==n){
break;
}
fast = fast->next;
i++;
}
/* fast and slow run together till fast be NULL,
* at this point, slow pointer got the right node to be deleted.
* last_slow pointer to get last pointer to slow.
*/
while(fast){
fast = fast->next;
last_slow = slow;
slow = slow->next;
}
if(last_slow){
last_slow->next = slow->next;
free(slow);/* free mem of node to be deleted */
}else{/* if last_slow is NULL, head will be deleted. */
head = head->next;
free(slow);
}
return head;
}