用于删除所选链接列表C中的元素的功能



嗨,我正在为学校创建一个程序,我必须:

  1. 创建结构
  2. 创建函数以打印我的链接列表
  3. 创建函数以插入有序元素
  4. 删除次要年份小于所选年份的元素我在最后一步创建了所有零件。你能帮我知道什么是正确的方法吗?这是我的代码:

结构:

typedef struct dimension {
int height;
int length;
} DIMENSION;
typedef struct pic {
DIMENSION d;
char name[50];
int year;
} PIC;
typedef struct node {
PIC p;
struct node *next;
} NODE;

打印列表:

void printPic(PIC p) {
printf("Autor: %snDimensionnHeight: %dnLength: %dnYear: %dn", p.name, p.d.height, p.d.length, p.year);
}
void printList(NODE *head) {
if(head->next==NULL) {
printf("No element in the list!n");
} else {
while(head->next != NULL) {
head = head->next;
printPic(head->p);
}
}
}

新图片(按面积尺寸排序(

int area(PIC p) {
return (p.d.height * p.d.length);
}
PIC createPic() {
PIC newPic;

printf("Author: ");
fgets(newPic.name, 50, stdin);
newPic.name[strlen(newPic.name)-1] = '';
printf("Height: ");
scanf("%d", &newPic.d.height);
printf("n");
printf("Length: ");
scanf("%d", &newPic.d.length);
printf("n");
printf("Year: ");
scanf("%d", &newPic.year);
printf("n");
printf("n");

return newPic;

}
void insertPic(NODE *head) {

NODE* newNode = malloc(sizeof(NODE));
newNode->p = createPic();
newNode->next = NULL;

if(head==NULL) {
head = newNode;
} else {
if(area(newNode->p) < area(head->p)) {
newNode->next = head;
head = newNode;
} else {
while(head->next != NULL && (area(newNode->p) > area(head->next->p))) {
head = head->next;
}
newNode->next = head->next;
head->next = newNode;
}
}

}

删除年份比所选年份小的元素:

已编辑,现在工作:

void deletePic(NODE *head, int year) {
if(head==NULL) {
printf("No element in the list!n");
} else {
while(head->next != NULL) {
if(head->next->p.year < year) {
NODE *p = head->next;
head->next = p->next;
free(p);
} else {
head = head->next;
}
}
}
}

MAIN:

int main() {

NODE *head = malloc(sizeof(NODE));
head->next = NULL;
int choice = -1;

while(choice != 0) {
printf("Select an action:n");
printf("Press 1 --> See listn");
printf("Press 2 --> Insert a new elementn");
printf("Press 3 --> Delete elements with a minor yearn");
printf("Press 0 --> Stop programn");
scanf("%d%*c", &choice);

if(choice==1) {
printList(head);
}
else if(choice==2) {
insertPic(head);
}
else if(choice==3) {
int year;
printf("Choose an yearnAll elements with a smaller year will be eliminatedn");
scanf("%d", &year);
deletePic(head, year);
}
else if(choice==0) {
printf("See you soon ;)n");
}
}

}

您的deletePic函数在多个地方被破坏。其中:

  • 取消引用不确定的指针yearNode
  • 比较器不正确(应使用<,而不是!=
  • free正在处理一个不确定的指针

第一个和最后一个都是灾难的处方。如果该功能实现了菜单所声称的功能,我认为你想要的是:

void deletePic(NODE *head, int year)
{
if (head == NULL)
{
printf("No element in the list!n");
}
else
{
while (head->next != NULL)
{
if (head->next->p.year < year)
{
NODE *p = head->next;
head->next = p->next;
free(p);
}
else
{
head = head->next;
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新