C语言用链表存储字符串

#include<stdio.h>
#include<malloc.h> 
typedef struct LNode{
	char str;
	struct LNode *next;
}LNode,*LinkList;
int main(){
	LNode* L;
	L=(LNode*)malloc(sizeof(LNode));
	L->next=NULL;
	LNode *s,*r=L;
	char ch;
	while(1){
	     ch=getchar();
	     if(ch=='\n'){
	     	break;
		 }
		s=(LNode*)malloc(sizeof(LNode));
		s->str=ch;	
		r->next=s;
		r=s;
	}
	r->next=NULL;
	LNode *m=L->next;
	while(m!=NULL){
		printf("%c",m->str);
		m=m->next;
	}
	return 0;
		
}

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 C 语言链表字符串的例子: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义结构体 struct node { char *str; struct node *next; }; // 创建节点 struct node* create_node(char *str) { struct node *new_node = malloc(sizeof(struct node)); new_node->str = malloc(strlen(str) + 1); strcpy(new_node->str, str); new_node->next = NULL; return new_node; } // 插入节点 void insert_node(struct node **head, char *str) { struct node *new_node = create_node(str); if (*head == NULL) { *head = new_node; } else { struct node *curr = *head; while (curr->next != NULL) { curr = curr->next; } curr->next = new_node; } } // 打印链表 void print_list(struct node *head) { while (head != NULL) { printf("%s ", head->str); head = head->next; } printf("\n"); } int main() { struct node *head = NULL; insert_node(&head, "Hello"); insert_node(&head, "world"); insert_node(&head, "!"); print_list(head); return 0; } ``` 以上代码演示了如何创建一个简单的链表存储字符串。在这个例子,我们定义了一个结构体 `node`,它包含一个字符串指针 `str` 和一个指向下一个节点的指针 `next`。通过 `create_node` 函数创建节点,通过 `insert_node` 函数将节点插入链表,通过 `print_list` 函数打印链表字符串。在 `main` 函数,我们创建了一个空链表 `head`,并通过 `insert_node` 函数将三个字符串插入链表,最后通过 `print_list` 函数打印链表字符串

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值