链接列表到C中的字符串

时间:2015-02-02 18:16:10

标签: c

给定一个在每个节点中有两位数的链表,将其转换为字符串(第一个节点有msb)。示例12-> 34-> 56-> 78应输出为“12345678” 请给我解答如何编码上述问题。

这是代码(从OP注释中复制),j索引出错了。

i = 0; 
j = 0; 
temp1 = head; 
while (temp1 != NULL) { 
    num = temp1->data; 
    i = i++; 
    j = i+2; 
    while (num != 0) { 
        ct = num % 10; 
        num = num / 10; 
        r[j-2] = ct+'0'; 
        j--;
    } 
    r[i+1] = ',';
    temp1 = temp1->ptr;
}
r[i-1] = '\0';

2 个答案:

答案 0 :(得分:0)

C有一些很棒的工具。您可以使用sprintf()直接获取字符串中的数据,因此无需将数字切成单个数字。

temp1 = head;
char c[3];
char r[MAX]="";
while (temp1 != NULL)
{
    num = temp1->data;
    sprintf(c,"%d",num);
    //printf("%s\n",c);
    strcat(r,c);
    temp1 = temp1->ptr;
}
printf("%s\n",r);

答案 1 :(得分:0)

您使用索引会导致麻烦,因为它过于复杂且难以理解。只需要一个索引。

#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100

typedef struct Node {
    int data;
    struct Node *ptr;
} node;

node* add_node(node *root, int id) {
    // Add a node to the list with begins at root, return new root
    node *n = malloc( sizeof (node) );
    if (n == NULL) {
        printf("Fatal Error: Out of memory!\n");
        exit(1);
    }
    n->data = id;
    n->ptr = root;
    return n;
}

void free_list(node *root) {
    // free the list which starts with root
    node *tmp;
    while (root) {
        tmp = root->ptr;    
        free(root);
        root = tmp;
    }
}

int main(void) {
    node *temp1, *head = NULL;
    char r[MAXLEN+1] = "";
    int i = 0;
    head = add_node(head, 78);
    head = add_node(head, 56);
    head = add_node(head, 34);
    head = add_node(head, 12);

    temp1 = head; 
    while (temp1 != NULL) {
        if (i+2 > MAXLEN) {
            printf ("Out of string space!\n");
            break;
        }
        r[i++] = '0' + temp1->data / 10;
        r[i++] = '0' + temp1->data % 10;
        r[i] = 0;
        temp1 = temp1->ptr;
    }
    printf ("%s\n", r);

    free_list(head);
    return 0;
}

节目输出:

12345678