C语言链表2
2026/6/11 17:42:49 网站建设 项目流程
#include<stdio.h> #include<stdlib.h> struct node{ int date; struct node* next; }; struct node* creat(int info){ //创建一个节点 struct node* newnode=(struct node*)malloc(sizeof(struct node)); if(newnode==NULL){ printf("error\n"); exit(1); } newnode->date=info; newnode->next=NULL; return newnode; } void add(struct node** head, int info){ //在链尾接上节点 struct node* newnode=creat(info); if(*head==NULL){ *head =newnode; return; } struct node* now=*head;//当前指针不为空 while(now->next!=NULL){ now=now->next; } now->next=newnode; } void coutout(struct node* head){ //遍历链表输出 struct node* now=head; printf("following is the list:\n"); while(now!=NULL){ printf("%d ",now->date); now=now->next; } printf("\n"); } void freelist(struct node* head){ //释放内存 struct node* t; while(head!=NULL){ t=head; head=head->next; free(t); } } void insert(struct node* head,int k,int date){ //插入节点 if(head==NULL){ printf("empty\n"); return; } struct node* now=head; for(int i=1;i<k&&now!=NULL;i++){ now=now->next; } if(now==NULL){ printf("over the list\n"); return; } struct node* newnode=creat(date); newnode->next=now->next; now->next=newnode; } void deletenode(struct node** head,int k){ if(*head==NULL){ printf("the list is empty\n"); return; } struct node* now=*head; struct node* prev=NULL; for(int i=1;i<k&&now!=NULL;i++){ prev=now; now=now->next; } if(now==NULL){ printf("over the list\n"); return; } if(prev==NULL){ *head=now->next; }else{ prev->next=now->next; } free(now); } int main(){ struct node* head=NULL; int num; scanf("%d",&num); while(num--){ int t; scanf("%d",&t); add(&head,t); } coutout(head); freelist(head); }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询