⑴ 用c語言編寫一個程序:用鏈表輸入很多和學生的信息,要求實現增、刪和查等功能
僅僅給你實現一個最基本的鏈表和功能,許多細節你自己添加,比如沒有判斷有沒有重復的學生信息輸入,如id重復。
還有刪除是依靠姓名刪除的,因為你的題目含糊不清,很多學生的信息具體是什麼你也沒有給出,只能給你個最基本的studentid 如果還有學科成績什麼的 自己在結構體中添加吧
後面你自己改了 最基本的給你寫好
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<malloc.h>
typedef struct student student;
struct student{
int sid;//student id
char sname[30];
struct student *next;
};
//鏈表
student *linklist;
int len;
void init_linklist()
{
linklist=NULL;
len=0;
}
bool addstudent(int studentid,char *name)
{
student *p;
p=(student*)malloc(sizeof(student));
strcpy(p->sname,name);
p->sid=studentid;
len++;
p->next=linklist;
linklist=p;
return 1;
}
bool removestudent(char *name)
{
student *p=linklist;
student *tmp=p;
while(p!=NULL&&strcmp(p->sname,name)!=0)
{
tmp=p;
p=p->next;
}
if(p==NULL)//no find
return 0;
if(tmp==p)//說明是表頭
{
linklist=p->next;
free(p);
len--;
return 1;
}
//非表頭
tmp->next=p->next;
free(p);
len--;
return 1;
}
student* findstudent(char *name)
{
student *p=linklist;
while(p!=NULL&&strcmp(p->sname,name)!=0)
p=p->next;
if(p==NULL)
return 0;
else
return p;
}
void printlist()
{
student *p=linklist;
while(p!=NULL)
{
printf("name:%s studentID:%d\n",p->sname,p->sid);
p=p->next;
}
}
int main(void)
{
init_linklist();
addstudent(111,"limin");
addstudent(222,"xiaoc");
printlist();
removestudent("xiaoc");
printlist();
char na[30];
int si;
printf("input the student you want to add:\n");
scanf("%s %d",na,&si);
addstudent(si,na);
printlist();
return 0;
}
⑵ c語言單鏈表鏈表如何插入多個節點
如果已知一個節點指針pre和一個節點指針cur,要把cur插入到pre節點之後,很顯然要保證鏈表不會斷開而丟失後面的節點,要先把後面的節點指針(指向lat的指針)保存下來,即有cur->next = pre->next,然後把cur連接的一串鏈表連接到pre後面,即pre->next = cur;
上面介紹了,在一個節點之後插入節點的情況。這是通常的情況。如果要向一個鏈表的頭部插入節點,就只需要將新節點的下一個指針指向鏈表的頭指針即可。
在這種情況下,有兩點要注意:
1,鏈表是否為空鏈表
2,要插入的節點是不是空指針。
代碼實現:
//向單鏈表中插入一個節點(插入在鏈開始處)
//輸入參數:單鏈表的頭指針和要插入的節點指針
//輸出參數:無
//返回值:指向單鏈表的頭指針
SingleList* Insert(SingleList *head,SingleList *node)
{
if(node == NULL)
{
return head;
}
else if(head == NULL)
{
return node;
}
node->next = head;
head = node;
return head;
}