[英]How do you get a data section from a Linked list to compare?
我剛剛開始學習鏈表,並弄亂了它,但后來遇到了一個問題。 我不確定如何訪問數據成員進行實際比較。 在我的代碼中,我提示用戶輸入成績,當他們輸入-1時,它表示已完成成績。 我的第一個想法是像在scanf中那樣獲得指向節點的指針以獲取數據,但是我無法將指針與整數進行比較。 有沒有辦法讓鏈表中的數據成員進行比較? 另外,指出其他錯誤也將不勝感激,因為我不太了解鏈表。 我有以下代碼:
int main() {
struct Node
{
int grade;
struct Node *next;
};
struct Node *head;
struct Node *first;
struct Node *temp = 0;
first = 0;
while (****** != -1) { //This is what I need the data from linked list for
head = (struct Node*)malloc(sizeof(struct Node));
printf("Enter the grade: \n ");
scanf("%d", &head -> grade);
if (first != 0) {
temp -> next = head;
temp = head;
}
else
{
first = temp = head;
}
}
}
您的代碼有很多問題:
1)不要直接掃描到列表中-使用臨時變量
2)始終檢查返回值
3)確保初始化變量,即head
嘗試類似:
struct Node
{
int grade;
struct Node *next;
};
int main() {
struct Node *head = NULL;
struct Node *temp;
int data;
while (1)
{
printf("Enter the grade: \n ");
if (scanf("%d", &data) != 1)
{
// Illegal input
exit(1);
}
if (data == -1) break; // Stop the loop
temp = malloc(sizeof *temp); // Allocate new element
if (temp == NULL)
{
// Out of mem
exit(1);
}
temp -> next = head; // Insert new element in the front of list
temp -> grade = data;
head = temp; // Move the front (aka head) to the new element
}
// .... add code that uses the list
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.