如何解决C 链表如何删除节点
所以我修复了“字符串名称”的问题,现在我想 添加一个通过其 ID 删除节点的函数,所以我尝试创建一个函数来定位具有请求 ID 的节点,但进展不顺利,因为它没有跟踪我输入的 ID。 完整代码如下:
#include <stdlib.h>
#include <stdio.h>
typedef struct stringData {
int id;
char *name;
int payment;
struct stringData *next;
} Node;
Node *addEmployee(int id,char *name,int payment) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->id = id;
newNode->name = strdup(name);
newNode->payment = payment;
newNode->next = NULL;
return newNode;
}
void insert(Node **link,Node *newNode) {
newNode->next = *link;
*link = newNode;
}
void removeEmployee(Node *head,int id){
while (head != NULL){
head = head->next;
if(head ->id == id){
printf("The employee exists.");
}
printf("The employee does not exists.");
}
}
void printList(Node *head) {
while (head != NULL) {
printf("----------------------------------\n");
printf("Name: %s\n",head->name);
printf("ID: %d\n",head->id);
printf("Payment: %d\n",head->payment);
printf("----------------------------------\n");
head = head->next;
}
}
int main(void)
{
int id;
char name[42];
int payment;
int input;
Node *head = NULL;
Node *tail = NULL;
Node *n;
n = addEmployee(1,"Dor",5000);
insert(&head,n);
tail = n;
n = addEmployee(2,"David",10000);
insert(&head,n);
tail = n;
printList(head);
removeEmployee(head,2);
while((input != 4)){
printf("\nPlease select 1 option:\n1) Add an employee - type 1\n2) Remove an employee - type 2\n3) Show a list of employees - type 3\n4) Exit - type 4\n");
scanf("%d",&input);
switch(input){
case 1:
printf("\nPlease enter the employee's id: ");
scanf("%d",&id);
printf("\nPlease enter the employee's name: ");
scanf("%41s",name);
printf("\nPlease enter the employee's payment: ");
scanf("%d",&payment);
n = addEmployee(id,name,payment);
insert(&head,n);
tail = n;
break;
case 2:
printf("Please enter the ID of the employee you would like to remove: ");
scanf("%d",&id);
break;
case 3:
printList(head);
break;
case 4:
printf("Good-bye");
break;
default:
printf("This is not an option!");
break;
}
}
return 0;
}
我不知道如何进入它,我对这个主题不是很熟悉,所以看看一些例子会很有帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。