此程序应从链接列表中删除节点(在我的情况下是10,20,30,...,100),这些数据与您输入的数字相等。它无法正常工作。它应该显示完整列表但它在10之后停止,给出选择号码和中断。
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
#include "LinkedList.c"
int main() {
int x;
int change=0;
LINK head, curr, currB, tail;
head = NULL;
curr = NULL;
currB = NULL;
tail = NULL;
create_list(&head, &curr, &tail);
print_list(head, curr);
ask_for_value(&x);
delete_node(head, curr, currB, tail, &change, x);
if (0 == change)
printf("\nValue %d is not on the list\n", x);
print_list(head, curr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
void create_list(LINK *head, LINK *curr, LINK *tail) {
int i;
for(i=10; i<100; i+=10) {
(*curr)=(LINK)malloc(sizeof(ELEMENT));
(*curr)->data = i;
if(i==10) {
(*curr)->next = NULL;
(*tail)=(*curr);
(*head)=(*curr);
}
else {
(*curr)->next = NULL;
(*tail)->next = (*curr);
(*tail)=(*curr);
}
}
}
void delete_node(LINK head, LINK curr, LINK currB, LINK tail, int *change, int x) {
int i;
if(head->data==x) {
curr=head;
head=curr->next;
free(curr);
(*change)=1;
exit(0);
}
if(tail->data==x){
curr=head;
while(curr->next!=tail)
curr=curr->next;
free(tail);
tail=curr;
tail->next=NULL;
(*change)=1;
exit(0);
}
curr=currB=head;
while(curr->data!=x || curr->next!=NULL){
currB=curr;
curr=curr->next;
}
if(curr->data!=x)
exit(0);
if(currB==curr){
head=curr->next;
free(curr);
(*change)=1;
exit(0);
}
currB->next=curr->next;
free(curr);
(*change)=1;
}
void print_list(LINK head, LINK curr)
{
curr=head;
if (curr!=NULL){
printf("%d >> ",curr->data);
curr = curr->next;
}
}
void ask_for_value(int *x) {
printf("Enter value which should be removed from the list\n");
scanf("%d", &x);
}
#ifndef LINKED_LIST_H_
#define LINKED_LIST_H_
struct linkedList{
int data;
struct linkedList *next;
};
typedef struct linkedList ELEMENT;
typedef struct linkedList *LINK;
void create_list(LINK *head, LINK *curr, LINK *tail);
void delete_node(LINK head, LINK curr, LINK currB, LINK tail, int *listChange, int x);
void print_list(LINK head, LINK curr);
void ask_for_value(int *x);
#endif
第二个文件是LinkedList.c,第三个文件是LinkedList.h
编辑:我已经更改了delete_node,可以使用除10之外的任何值。
void delete_node(LINK head, LINK curr, LINK currB, LINK tail, int x) {
curr=currB=head;
while(curr->data!=x && curr->next!=NULL) {
currB=curr;
curr=curr->next;
}
if(head->data==x) {
head=curr->next;
free(currB);
}
else if(tail->data==x) {
tail=currB;
tail->next=NULL;
free(curr);
}
else if(curr->data!=x) {
printf("Element with given value could not be found!\n");
}
else{
currB->next=curr->next;
free(curr);
}
}
答案 0 :(得分:1)
在ask_for_value()
函数
scanf("%d", &x);
应该是
scanf("%d", x);
另外,请勿#include
.c
个文件。它们是要编译的。
接下来,您的delete_node()
功能不正确。它将通过遇到exit(0)
来终止程序的执行,这可能不是想要的。您可以改为使用return 0
。