c - 链表直到第二次迭代才添加节点

标签 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 是垃圾,我只是不想费心学习如何做其他事情)

感谢您的帮助!

最佳答案

您的代码:

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

应该是:

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

并且head需要初始化。

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

关于c - 链表直到第二次迭代才添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36902076/

相关文章:

c - 当输入是阶数大于 2 的矩阵时,为什么会出现段错误?

c - 指针和内存地址

C:输出错误链表和写入和读取文件

performance - 用于实现堆栈的链表与动态数组

c - 我应该相信 C 中的短通常是 2 个字节吗?

使用多个线程并发写入文件

c - 在链接列表的函数中传递指针

python - Cython实现不比纯python快

java - 搜索 Java 链表

c - 警告 : passing argument 2 of ‘memcpy’ makes pointer from integer without a cast [enabled by default]