c语言 将一个链表转化为字符串
时间: 2023-08-12 11:06:54 浏览: 108
要将一个链表转化为字符串,可以按照以下步骤进行:
1. 定义一个字符数组,用于存储转化后的字符串;
2. 遍历链表,将每个节点的值转化为字符,并拼接到字符数组中;
3. 在字符数组末尾添加一个结束符 '\0',表示字符串的结束。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
char* listToString(struct ListNode* head) {
// 计算链表长度
int len = 0;
struct ListNode* p = head;
while (p != NULL) {
len++;
p = p->next;
}
// 分配字符数组空间
char* str = (char*)malloc(sizeof(char) * (len * 2 + 1));
if (str == NULL) {
printf("Memory allocation failed.\n");
return NULL;
}
// 遍历链表,将每个节点的值转化为字符
p = head;
int i = 0;
while (p != NULL) {
str[i++] = p->val + '0';
str[i++] = '-';
p = p->next;
}
// 在字符数组末尾添加一个结束符
str[i] = '\0';
return str;
}
int main() {
// 创建一个链表
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->val = 3;
head->next->next->next = NULL;
// 将链表转化为字符串
char* str = listToString(head);
printf("The string representation of the list is: %s\n", str);
// 释放链表和字符数组的内存
struct ListNode* p = head;
while (p != NULL) {
struct ListNode* q = p->next;
free(p);
p = q;
}
free(str);
return 0;
}
```
该代码中,listToString 函数接受一个链表的头节点指针作为参数,返回一个指向字符数组的指针。程序运行结果如下:
```
The string representation of the list is: 1-2-3-
```