LeetCode 19题:删除链表倒数第n个节点

文章目录

题目

思路

代码

总结


题目

给你一个链表,删除链表的倒数第 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;
}

总结

以上就是今天要讲的内容,继续练习吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流光焰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值