【问题标题】:Store the past user entered commands into a linked list将过去用户输入的命令存储到链表中
【发布时间】:2015-01-28 23:11:13
【问题描述】:

我有一个程序将用户输入读入一个名为 inputBuffer 的 char 数组中,并且还存储 char 数组的长度:

length = read(STDIN_FILENO, inputBuffer, 80);

我希望能够存储过去的 10 个输入,以便可以访问它们。当第 11 个输入进来时,我需要删除第一个输入,所以现在只存储输入 2-11。这可以通过某种方式使用链表来完成吗?

【问题讨论】:

  • 当然,您可以使用链表来做到这一点。试一试,如果您遇到困难,请发布更具体的问题,包括您的链表代码。还要看一个循环缓冲区。那是一种特殊的数据结构,可能更适合这项任务。 en.wikipedia.org/wiki/Circular_buffer

标签: c arrays input linked-list


【解决方案1】:

此答案使用 OP 要求的保存字符串和长度的结构的环形缓冲区。当缓冲区结束时,先前的字符串内存被释放并初始化新记录。最旧的记录位于索引 first_rec 处,并且有 num_recs 记录。为了这个例子,我的主循环结束测试是当有一个空白条目时。我在初始化时有点懒惰,假设静态数组的字符串指针初始化为NULL

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

#define RECORDS 10
#define BUFSIZE 999

typedef struct {
    int length;
    char *input;
    } inpstruct;

inpstruct history [RECORDS];
int first_rec;
int num_recs;

void show_history (void) {
    int i, index;
    for (i=0; i<num_recs; i++) {
        index = (first_rec + i) % RECORDS;
        printf("Index: %-2d Length: %-3d Input: %s\n", index, 
                history[index].length, history[index].input);
    }
}

int main(void) {
    char buffer [BUFSIZE+1];
    int len, index;
    while (fgets(buffer, BUFSIZE, stdin) != NULL) {
        len = strlen(buffer);
        if (len && buffer[len-1]=='\n')
            buffer [--len] = 0;             // truncate newline
        if (len == 0)
            break;
        index = (first_rec + num_recs) % RECORDS;
        if (history[index].input != NULL)   // release previous record
            free (history[index].input);
        if ((history[index].input = malloc(len+1)) == NULL) {
            perror ("malloc() failure");
            return 1;
        }
        strcpy (history[index].input, buffer);
        history[index].length = len;
        if (num_recs < RECORDS)
            num_recs++;
        else
            first_rec = (first_rec + 1) % RECORDS;
        show_history();
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多