将一个字符串s中的数字符依次构造一个单链表H,用c语言写
时间: 2024-03-27 19:35:06 浏览: 15
下面是一个简单的C语言代码实现:
```c
#include<stdio.h>
#include<stdlib.h>
//定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
//函数声明
struct ListNode* createList(char *s);
void printList(struct ListNode* head);
int main() {
char s[] = "12345";
struct ListNode* head = createList(s);
printList(head);
return 0;
}
//创建链表函数
struct ListNode* createList(char *s) {
struct ListNode *head = NULL, *pre = NULL, *newNode = NULL;
int num;
for(int i = 0; s[i] != '\0'; i++) {
if(s[i] >= '0' && s[i] <= '9') {
num = s[i] - '0'; //将字符转为数字
newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); //创建新节点
newNode->val = num;
newNode->next = NULL;
if(head == NULL) { //如果链表为空,将新节点设为头节点
head = newNode;
}
else { //如果链表不为空,将新节点插入到链表尾部
pre->next = newNode;
}
pre = newNode;
}
}
return head;
}
//遍历链表并输出函数
void printList(struct ListNode* head) {
struct ListNode *p = head;
while(p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
```
这个代码会将字符串中的数字构造成一个单链表,并输出链表中的元素。