c - 结构体将 LIFO 转换为 FIFO

标签 c struct

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

typedef struct elt {
    struct elt *next; // Elément suivant
    struct elt *precedent;
    int value; // Valeur stockée dans le noeud
} ELT, *pELT;
pELT head=NULL;

pELT addElt(pELT head, int v) {
    pELT n;

    n=malloc(sizeof(ELT));
    n->value = v;
    n->next = head;

    return n;
}

void printElts(pELT l) {
    pELT p;

    for(p = l; p; p=p->next) {
        printf("Valeur : %d\n", p->value);
    }
}

int main(void) {
    head = addElt(head, 1);
    head = addElt(head, 2);
    head = addElt(head, 3);
    printElts(head);
    return EXIT_SUCCESS;
}

我想将这个 LIFO(后进先出)结构转换为 FIFO(先进先出)。 我不想改变主要。我只想以 FIFO 而不是 LIFO 方式打印

最佳答案

现在您将元素“添加”到列表中,这是一种 stack :

n = malloc(sizeof(ELT));
n->value = v;
n->next = head;

如果您想将元素“追加”到列表末尾,使其成为一种 queue ,您只需将“添加元素”任务沿着列表向下传递(例如递归地),直到到达末尾:

pELT addElt(pELT head, int v) {
  if "head->next is NULL" {
    // end of list reached, put "v" here
  } else { 
    // we're in the middle of the list, go on with the child:
    head->next = addElt(head->next, v)
  }
}

这只是一个想法,实现起来非常简单

关于c - 结构体将 LIFO 转换为 FIFO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24272971/

相关文章:

c - 为什么我对 printf() 的调用无法在控制台中显示正确的字符?

c - C 函数 memccpy() 的实现如何在以下输入上不出现段错误?

c - 为什么有时不需要在 C 中分配内存?

python - 在 Python 中使用 struct.unpack 从文件中读取整数

c++ - 尝试将指针与结构一起使用时出错

c - 释放链表中的节点

java - 从纯 c 方法调用 JNI 方法

c - 是否可以访问 C 中的 32 位寄存器?

c++ - 连接到网络的所有设备的列表

c - 什么是标签 namespace ?