/*
总结:
1、首先定位到第n个节点,然后将其前一个节点的next指向其后一个节点;
2、在head节点前设置dummy节点便于操作;
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdio.h>
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode *dmyNode=malloc(sizeof(struct ListNode));
dmyNode->next=head;
struct ListNode *ps=head,*ahead=dmyNode,*nNode,*behind;
int cnt=0;
while(ps!=NULL)
{
cnt++;
ps=ps->next;
}
if(cnt==1)
{
return NULL;
}
cnt=cnt-n;
while(cnt>0)
{
ahead=ahead->next;
cnt--;
}
nNode=ahead->next;
behind=nNode->next;
ahead->next=behind;
return dmyNode->next;
}
力扣C语言-19. 删除链表的倒数第 N 个结点
最新推荐文章于 2025-05-20 13:23:42 发布