题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

#include <stdio.h>
#include<stdlib.h>
typedef struct STLNode
{
    int data;
    struct STLNode* next;
}STLNode;
void InsertAfter(STLNode** pphead,int x,int pos)//指定数值后面插入
{
    STLNode* head=*pphead;
    STLNode* newnode=(STLNode*)malloc(sizeof(STLNode));
    newnode->data=x;
    if(head==NULL)
    {
        head=newnode;
        head->next=NULL;
        return;
    }
    while(head->data!=pos)
    {
        head=head->next;
    }
    newnode->next=head->next;
    head->next=newnode;
    return;
}
void Erase(STLNode** pphead,int del)//删除指定数值节点
{
    STLNode* pre=*pphead;
    STLNode* cur=*pphead;
    if(pre->data==del)
    {
        *pphead=pre->next;
        free(pre);
        return;
    }
    while(pre->next->data!=del)
    {
        pre=pre->next;
    }
    cur=pre->next;
    pre->next=cur->next;
    free(cur);
    cur=NULL;
    return;
}
void Print(STLNode* phead)//打印链表
{
    while(phead!=NULL)
    {
        printf("%d ",phead->data);
        phead=phead->next;
    }
    return;
}
int main()
{
    int i=0,n=0,x=0,del,arr[1000][2];
    STLNode* plist=(STLNode*)malloc(sizeof(STLNode));
    scanf("%d %d",&n,&x);
    plist->data=x;
    plist->next=NULL;
    for(i=1;i<n;i++)
    {
        scanf("%d %d",&arr[i][0],&arr[i][1]);
        InsertAfter(&plist,arr[i][0],arr[i][1]);
    }
    scanf("%d",&del);
    Erase(&plist,del);
    Print(plist);//题目当中省略了销毁链表和释放动态内存等,可自行添加
    return 0;
}

全部评论

相关推荐

程序员小白条:找的太晚,别人都是大三实习,然后大四秋招春招的,你大四下了才去实习,晚1年
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务