c - C语言如何给链表的每个节点添加描述

标签 c singly-linked-list

所以我已经构建了一个链接列表,但我想为输出中创建的每个节点添加描述。代码是:

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

//Structure to create Linked list
typedef struct iorb {
int base_pri;
struct iorb *link;
char filler[100];
} IORB;

IORB * Build_list(int n);
void displaylist(IORB * head);

int main(){
int n=0;
IORB * HEAD = NULL;
printf("\nHow many blocks you want to store: ");
scanf("%d", &n);
HEAD = Build_list(n);
displaylist(HEAD);

return 0;
}

IORB * Build_list(int n){
int i=0;

IORB*head=NULL; //address of first block
IORB*temp=NULL; //temporary variable used to create individual block
IORB*p=NULL;    // used to add the block at the right position

for(i=0;i<n;i++){
        //individual block is created

    temp = (IORB*)malloc(sizeof(IORB));
    temp->base_pri = rand() % 10;         //random values are generated to 
   be stored in IORB blocks
    temp->link = NULL;                    //Next link is equal to NULL

    if(head == NULL){            //If list is empty then make temp as the 
   first block
        head = temp;
    }
    else{
        p = head;
        while(p->link != NULL)
            p = p->link;
            p->link = temp;
    }
}

return head;
}

void displaylist(IORB * head){

IORB * p = head;
printf("\nData entered for all the blocks:\n");

while(p != NULL)
{
printf("\t%d", p->base_pri);
p = p->link;
}
}

因此,使用数组“filler[100]”来进行描述。为了给出更好的想法,我希望描述如下:

block 1 的数据为 3

block 2的数据为0

block 3的数据是9

block 4的数据是7

block 5的数据是4

其中 3,0,9,7,4 是随机生成的值。

最佳答案

您可以使用 snprintf 格式化字符串:

snprintf(temp->filler, sizeof temp->filler, "Data for block %d is %d", i, temp->base_pri);

关于c - C语言如何给链表的每个节点添加描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186463/

相关文章:

c - 如何将对象添加到单向链表

c - 插入到简单链接列表(任何位置、前端、末尾、中间)

C:删除链表

c - 使用链表分隔偶数和奇数的函数

c - 为什么 C 函数不能返回数组?

sql嵌入c程序对几个表进行排名

c - 这个C代码有什么问题?

c - C 中的通用数据类型的任何库?

c - 你用什么cscope引用卡?

python - LinkedList删除功能正在删除2个节点