2017-10-10 39 views
0

我刚刚开始学习链接列表,并搞乱了它,但后来遇到了问题。我不确定如何访问数据成员以实际比较它。在我的代码中,我提示用户输入等级,当他们输入-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; 
     } 
    } 
} 
+0

当学习链表(或者任何其他复杂结构)时,天空会拉出一张8.5x11的纸,一支铅笔,并绘制节点和节点指针将它们链接在一起。举一个小例子,4-5个节点,然后找出你的'add','del','find'等函数。使用这些文件作为参考,以获得正确的链接和循环。它需要的时间远远少于无休止地看着希望获得灵感的屏幕:')' –

回答

0

有一些问题与您的代码:

1)不要直接扫描到列表中 - 用一个临时变量

2)经常检查返回值

3)确保初始化变量,即头

试着这么做:

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; 
} 
相关问题