[蓝蓝计算机考研算法二期]-day16

65 阅读1分钟

22、给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。

代码:

//22、给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。
#include <stdio.h>
#include <stdlib.h>
struct LNode{
    int val;
    struct LNode*next;
};
//创建链表
struct LNode *createlist(){
    int val=0;
    scanf("%d",&val);
    struct LNode *head=NULL,*p=NULL,*q=NULL;
    while(val!=-1){
        p=(struct LNode*)malloc(sizeof (struct LNode));
        p->val=val;
        p->next=NULL;
        if(head==NULL){
            head=p;
            q=p;
        }else{
            q->next=p;
            q=p;
        }
        scanf("%d",&val);
    }
    return head;
}

//删除节点
struct LNode *deletelist(struct LNode *head){
    int del=0;
    struct LNode *pre=head,*current=head->next;
    scanf("%d",&del);
    if(head==NULL){
        return 0;
    }
    //删除为头节点
    if(head!=NULL&&head->val==del){
        pre=head;
        head=head->next;
        free(pre);
        return head;

    }
    //删除不是头节点
    while(current!=NULL&&current->val!=del){
        pre=current;
        current=current->next;
    }
    if(current!=NULL){
        struct LNode*temp=current;
        pre->next=temp->next;
        free(temp);
    }
    return head;


}


//打印
void printlist(struct LNode*head){
    struct LNode*cur=head;
    while(cur!=NULL){
        printf("%d ",cur->val);
        cur=cur->next;
    }
}

int main(){
    struct LNode*list = createlist();
    struct LNode *result=deletelist(list);
    printlist(result);

}