如何用C语言向链表的每个节点添加描述

时间:2018-05-05 06:31:06

标签: 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;
}
}

所以,数组&#34;填充[100]&#34;用于给出描述。为了更好的主意,我希望描述如下:

块1的数据为3

块2的数据为0

块3的数据是9

方框4的数据是7

块5的数据是4

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

1 个答案:

答案 0 :(得分:1)

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

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