题目
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
提示:
- 链表中结点的数目为
sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
思路
这道题并不难,先将链表遍历一遍,得到链表长度len,根据 n 的值确定要删除节点的位置len-n+1,按顺序经过len-n个节点后,删除下一个节点即可
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
}Node;
struct ListNode* removeNthFromEnd(struct ListNode* head, int n);
void Creat(struct ListNode* head,int n);
int main()
{
int n;
struct ListNode* head=(struct ListNode*)malloc(sizeof(struct ListNode));
head->next=NULL;
scanf("%d",&n);
Creat(head,n);
int last;
scanf("%d",&last);
head=removeNthFromEnd(head,last);
Node*temp=head->next;
for(;temp!=NULL;temp=temp->next)
printf("%d ",temp->val);
return 0;
}
void Creat(struct ListNode* head,int n)
{
Node*end,*ins;
end=head;
for(int i=0;i<n;i++)
{
ins=(Node*)malloc(sizeof(Node));
int a;
scanf("%d",&a);
ins->val=a;
ins->next=NULL;
end->next=ins;
end=ins;
}
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode*temp;
int len=0;
for(temp=head->next;temp!=NULL;temp=temp->next)
{
len++;//获得长度
}
int target=len-n,i=0;
temp=head;
for(;i<target;temp=temp->next,i++);//遍历到target
temp->next=temp->next->next;//删除节点
return head;
}
总结
以上就是今天要讲的内容,继续练习吧。