链接列表在第二次迭代之前不添加节点

时间:2016-04-27 22:29:32

标签: c linked-list

我正在研究FIFO页面替换算法并使其几乎正常工作。我的代码使用scanf()读取页码,然后将该项添加到链接列表中,最多16页。但是,如果页面已存在于列表中,则不会再将页面添加到此列表中。有三个页面框架(插槽)。一切正常,但是,在scanf()读取另一个要添加到列表的整数之前,它不会将该项添加到列表中。我完全糊涂了。

#include<stdio.h>
#include<stdlib.h>

typedef struct node {
    int num;
    struct node * next;
} node_t;

void print_list(node_t * head) {
    node_t * current = head;
    while (current != NULL) {
        printf("%d\n", current->num);
        current = current->next;
    }
}

int fault(node_t * head, int check) {
    node_t * current = head;
    while(current->next != NULL){
        if(current->num == check)
            return 0;
        current = current->next;
    }
    return 1;
}

void addNode(node_t * head, int num) {
    node_t * current = head;
    while (current->next != NULL) {
        current = current->next;
    }

    /* now we can add a new variable */
    current->next = malloc(sizeof(node_t));
    current->next->num = num;
    current->next->next = NULL;
}

int pop(node_t ** head) {
    int retnum = -1;
    node_t * nextNode = NULL;
    if (*head == NULL) {
        return -1;
    }
    nextNode = (*head)->next;
    retnum = (*head)->num;
    free(*head);
    *head = nextNode;
    return retnum;
}

///////////////////////////////////////////////////////

int main(){
    int num;
    int faults = 0;
    int n = 0;
    int j = 0;
    node_t * head = malloc(sizeof(node_t));
    if (head == NULL) {
        return 1;
    }
    head->num = -1;
    printf("Input page number up to 16 pages. Enter 'q' to quit.\n");
    for(j=0;j<16;j++){
        if(scanf("%d\n",&num) == 1) {

            if (fault(head, num) == 1 && n < 3) {
                n++;
                faults++;
                addNode(head, num);
            }
            else if (fault(head, num) == 1 && n >= 3) {
                pop(&head);
                addNode(head,num);
                faults++;
            }   
        }   
        else{
           int c = getchar();
           if( c == 'q' ){
               break;
           }
        }
        if (n == 1 && faults == 1)
            pop(&head);
        printf("\nPage Table:\n");
        print_list(head);
        printf("\nInput page number: \n");
    }
    printf("Number of page faults: %d\n", faults);
}

我通过gdb运行它,直到第二个整数被扫描后才调用addNode函数。

(是的,我知道scanf是垃圾,我只是不想学习如何做别的事情)

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您的代码:

    if(scanf("%d\n",&num) == 1) {

应该是:

    if(scanf("%d",&num) == 1) {

头部需要初始化。

    node_t * head = malloc(sizeof(node_t));
    if (head == NULL) {
    return 1;
}
head->next = NULL;