创建一个程序,使用链表存储歌曲播放列表。该程序应该能够:
- 在播放列表的前面插入一首新歌
- 在播放列表后面插入新歌
- 在播放列表之间插入新歌
- 删除播放列表中的任何歌曲
- 显示播放列表
我使用评论提到了错误
#include <stdio.h>
#include <stdlib.h>
struct node
{
char str[];
struct node* next;
} *
void insertAtBeginning(struct Node** ref, char data[]) //expecte indentifier or '(' before 'void'
{
// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
// insert the item
new_node->item = data;
new_node->next = (*ref);
// Move head to new node
(*ref) = new_node;
}
// Insert a node after a node
void insertAfter(struct Node* node, char data[])
{
if (node == NULL)
{
printf("the given previous node cannot be NULL");
return;
}
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); //error: invalid application of 'sizeof' to incomplete type 'struct Node'
new_node->item = data; // error: dereferencing pointer to imcomplete type 'struct Node'
new_node->next = node->next;
node->next = new_node;
}
void insertAtEnd(struct Node** ref, char data[
])
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // error: invalid application of 'sizeof' to imcomplete type 'struct Node'
struct Node* last = *ref;
new_node->item = data; // error: dereferencing pointer to imcomplete type 'struct Node'
new_node->next = NULL;
if (*ref == NULL)
{
*ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
void deleteNode(struct Node** ref, char key[])
{
struct Node* temp = *ref, * prev;
if (temp != NULL && temp->item == key) // error: dereferencing pointer to imcomplete type 'struct node'
{
*ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->item != key)
{
prev = temp;
temp = temp->next;
}
// If the key is not present
if (temp == NULL)
return;
// Remove the node
prev->next = temp->next;
free(temp);
}
// Print the linked list
void printList(struct Node* node)
{
while (node != NULL)
{
printf(" %s ", node->item); // error: dereferencing the pointer to imcomplete type 'struct Node'
node = node->next;
}
}
int main()
{
char song[50];
struct Node* head = NULL;
insertAtEnd(&head, "red");
insertAtBeginning(&head, "dangerously");
insertAtBeginning(&head, "attention");
insertAtEnd(&head, "blue");
insertAfter(head->next, 5); // error: dereferencing the pointer to imcomplete type 'struct Node'
printf("Linked list: ");
printList(head);
printf("nAfter deleting an element: ");
deleteNode(&head, "random");
printList(head);
}
您的程序甚至没有编译,存在许多问题。
最重要的是:
- 您声明了
struct Node
,但在代码中使用了struct node
。标识符区分大小写 struct node
的声明以*
结束,而不是以;
结束- 使用数组时没有声明像
char str[];
而不是char str[100];
这样的大小,这在C中毫无意义 - 您使用字段
item
,而您声明的结构没有名为item
的字段
你应该阅读C学习材料中关于字符串的章节。C中没有实际的字符串类型,不能使用=
运算符分配字符串,请使用strcpy
。