【问题标题】:Linked Lists to strings in C链接列表到 C 中的字符串
【发布时间】:2015-02-02 18:16:10
【问题描述】:

给定一个每个节点有两位数字的链表,将其转换为字符串(第一个节点有 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';

【问题讨论】:

  • 在一行中打印所有节点。
  • 在 stackoverflow.com 上,预计您将解决您的问题并展示您已完成的工作以及遇到的问题。
  • 我应该将值返回给主函数@hacks
  • i = 0; j = 0; temp1 = 头; while (temp1 != NULL) { num = temp1->data;我=我++; j = i+2;而 (num != 0) { ct = num % 10;数 = 数 / 10; r[j-2] = ct+'0'; j——; } r[i+1] = ','; temp1 = temp1->ptr; } r[i-1] = '\0'; j 索引出了问题..@Simon Gibbons
  • i = i++;未定义的行为

标签: c


【解决方案1】:

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);

【讨论】:

    【解决方案2】:

    您对索引的使用导致了麻烦,因为它太复杂且难以遵循。只需要一个索引。

    #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
    

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 2019-05-12
      • 1970-01-01
      • 2021-01-10
      • 2016-07-23
      • 2021-05-25
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多