如何在C++中创建链表列表?

How to Create a List of Linked List in C++?

本文关键字:链表 列表 创建 C++      更新时间:2023-10-16

我正在尝试在C++中创建链表数组。

我想创建一个链表,可以添加/删除新的学生姓名和ID。 以下是节点的结构:

struct node
{
char name[50];
char id[50];
struct node *next;
}*start=NULL,*prev;
typedef struct node node;

怎么做?

法典:

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
struct node
{
char name[50];
char type[50];
struct node *next;
}*start=NULL,*prev;
typedef struct node node;
void menu();
void insertion();
void finder();
void table();
void deletion();
int main()
{
//node *table[57];
while(1)
{
menu();
}
return 0;
}
void menu()
{
int choice;
printf("nSymbol Table Menun1. Insert.n2. Find.n3. Show Table.n4. Delete.n");
scanf("%d",&choice);
//system("cls");
if(choice==1)insertion();
else if(choice==2)finder();
else if(choice==3)table();
else if(choice==4)deletion();
}
int Hashing(node *temp)
{
int h,len,i,asc,sum=0;
printf("nHashingn");
len=strlen(temp->name);
for(i=0; i<len; i++)
{
asc=temp->name[i];
sum=sum+asc;
}
h=sum%57;
return h;
}
void insertion()
{
int index;
node *temp;
if (start == NULL)
{
start =(node*)malloc(sizeof(node));
temp=start;
printf("Insert Name: ");
scanf("%s",start->name);
index=Hashing(temp);
printf("Index: %dn",index);
printf("nInsert Type: ");
scanf("%s",start->type);
start->next=NULL;
prev=start;
}
else
{
temp=(node*)malloc(sizeof(node));
printf("Insert Name: ");
scanf("%s",temp->name);
index=Hashing(temp);
printf("Index: %dn",index);
printf("nInsert Type: ");
scanf("%s",temp->type);
temp->next= NULL;
prev->next=temp;
prev=temp;
}
}
void finder()
{
node *temp;
char key1[50];
char key2[50];
printf("nInsert Search Key: ");
temp=start;
scanf("%s%s",key1,key2);
while(temp!=NULL)
{
if((strcmp(temp->name,key1)==0) && (strcmp(temp->type,key2)==0))
{
printf("FOUNDn");
}
temp=temp->next;
}
}
void table()
{
printf("nFull Tablenn");
node *temp;
printf("Linked list = ");
temp=start;
if(temp==NULL) printf("No listn");
while(temp!=NULL)
{
printf("%s,%s -> ",temp->name,temp->type);
temp=temp->next;
if(temp==NULL)printf("NULLn");
}
}
void deletion()
{
node *temp,*temp1;
char del1[50];
char del2[50];
temp=start;
printf("Delete Name: ");
scanf("%s",del1);
printf("nDelete Type: ");
scanf("%s",del2);
if((strcmp(temp->name,del1)==0) && (strcmp(temp->type,del2)==0))
{
start=start->next;
free(temp);
}
else
{
while ((temp->next->next!=NULL)&&(strcmp(temp->next->name,del1)!=0))
{
temp=temp->next;
}
if ((temp->next==NULL) &&(strcmp(temp->name,del1)!=0))
printf("nNot Foundn");
else
{
temp1=temp->next;
temp->next=temp1->next;
free(temp1);
}
}
printf("DELETEDn");
}

创建一个node数组,并分别初始化它们中的每一个。

node *array = malloc(NUMBER_OF_NODES*sizeof(node *));
int i;
for(i=0; i< NUMBER_OF_NODES; i++)
{
/* this part is optional - you might want to leave some of the cells uninitialized */
array[i] = malloc(sizeof(node)); /* notice that we need to allocate space for a node - not (node *)!
}