用C语言编写1.构造链串结构并初始化链串; 2.给链串赋值(链表的建立,思考:用头插法还是尾插法),注意:在此过程中同时还要把字符串的长度赋给对应的量; 3.打印字符串的内容(链串的遍历)。
时间: 2024-03-14 19:43:47 浏览: 15
好的,我来为您解答这个问题。
首先,我们需要定义链串结构体,包含一个字符变量和一个指向下一个节点的指针:
```c
typedef struct node {
char data;
struct node *next;
} Node, *LinkList;
```
然后,我们可以编写一个函数来初始化链串:
```c
void initList(LinkList *L) {
*L = (LinkList)malloc(sizeof(Node));
(*L)->next = NULL;
}
```
在这个函数中,我们首先为链串分配内存空间,然后将其下一个节点指针设为 NULL。
接下来,我们可以编写一个函数来给链串赋值:
```c
void assignList(LinkList L, char *str) {
int len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = str[i];
newNode->next = L->next;
L->next = newNode;
}
}
```
在这个函数中,我们首先计算出字符串的长度,然后从字符串末尾开始遍历,为每个字符创建一个新节点,并使用头插法将其插入到链串中。
最后,我们可以编写一个函数来打印链串的内容:
```c
void printList(LinkList L) {
Node *p = L->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\n");
}
```
在这个函数中,我们遍历链串中的每个节点,并打印出它们的字符值。
完整的代码如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char data;
struct node *next;
} Node, *LinkList;
void initList(LinkList *L) {
*L = (LinkList)malloc(sizeof(Node));
(*L)->next = NULL;
}
void assignList(LinkList L, char *str) {
int len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = str[i];
newNode->next = L->next;
L->next = newNode;
}
}
void printList(LinkList L) {
Node *p = L->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkList L;
char str[] = "Hello, world!";
initList(&L);
assignList(L, str);
printList(L);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)