创建结构体:

struct Node{
    int date;
    struct Node*next;
};

创建表头:

struct Node*creatlist(){
    struct Node*headNode;
    headNode=(struct Node*)malloc(sizeof(struct Node));
    headNode->date=123;
    headNode->next=NULL;
    return headNode;
} 

创建结点:

struct Node*creatNode(int date){
    struct Node*newNode=(struct Node*)malloc(sizeof(struct Node));
    newNode->date=date;
    newNode->next=NULL;
    return newNode;
}

打印输出:

void printlist(struct Node*headNode){
    struct Node*pmove=headNode;
    while(pmove){
        printf("%d\t",pmove->date);
        pmove=pmove->next;
    }
    printf("\n");
}

头插法:

void add(struct Node*headNode,int date){
    struct Node*newNode=creatNode(date);
    newNode->next=headNode->next;
    headNode->next=newNode;
}

指定删除:

void shanchu(struct Node*headNode,int posdate){
    struct Node*posNode=headNode->next;
    struct Node*posNodeFront=headNode;
    if(posNode==NULL)
    printf("无法删除,链表为空");
    else{
        while(posNode->date!=posdate){
            posNodeFront=posNode;
            posNode=posNodeFront->next;
            if(posNode==NULL){
                printf("没有找到相关信息,无法删除");
                break;
            }
        }
        posNodeFront->next=posNode->next;
        free(posNode);
    } 
}

代码如下:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Node{
    int date;
    struct Node*next;
};
struct Node*creatlist(){
    struct Node*headNode;
    headNode=(struct Node*)malloc(sizeof(struct Node));
    headNode->date=999;
    headNode->next=NULL;
    return headNode;
} 
struct Node*creatNode(int date){
    struct Node*newNode=(struct Node*)malloc(sizeof(struct Node));
    newNode->date=date;
    newNode->next=NULL;
    return newNode;
}
void printlist(struct Node*headNode){
    struct Node*pmove=headNode;
    while(pmove){
        printf("%d\t",pmove->date);
        pmove=pmove->next;
    }
    printf("\n");
}
void add(struct Node*headNode,int date){
    struct Node*newNode=creatNode(date);
    newNode->next=headNode->next;
    headNode->next=newNode;
}
void shanchu(struct Node*headNode,int posdate){
    struct Node*posNode=headNode->next;
    struct Node*posNodeFront=headNode;
    if(posNode==NULL)
    printf("无法删除,链表为空");
    else{
        while(posNode->date!=posdate){
            posNodeFront=posNode;
            posNode=posNodeFront->next;
            if(posNode==NULL){
                printf("没有找到相关信息,无法删除");
                break;
            }
        }
        posNodeFront->next=posNode->next;
        free(posNode);
    } 
}
int main(int argc, char *argv[]) {
    struct Node*list=creatlist();
    add(list,1);
    add(list,2);
    add(list,3);
    shanchu(list,2);
    printlist(list);
}

输出结果:

999     3       1

--------------------------------
Process exited after 0.09419 seconds with return value 10
请按任意键继续. . .

Last modification:March 20th, 2021 at 05:01 pm
如果觉得我的文章对你有用,请随意赞赏