首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在单个链表中插入字符串

在单个链表中插入字符串,通常意味着你要将字符串的字符逐个插入到链表的节点中。下面是一个简单的例子,展示了如何在C语言中实现这一功能。我们将创建一个链表,每个节点包含一个字符,然后遍历字符串,将每个字符添加到链表中。

首先,定义链表节点的结构体:

代码语言:javascript
复制
typedef struct Node {
    char data;
    struct Node* next;
} Node;

接下来,创建一个函数来在链表末尾插入新节点:

代码语言:javascript
复制
void insertAtEnd(Node** head_ref, char new_data) {
    Node* new_node = (Node*)malloc(sizeof(Node));
    Node* last = *head_ref;
    new_node->data = new_data;
    new_node->next = NULL;
 
    if (*head_ref == NULL) {
        *head_ref = new_node;
        return;
    }
 
    while (last->next != NULL)
        last = last->next;
 
    last->next = new_node;
    return;
}

现在,创建一个函数来将整个字符串插入链表:

代码语言:javascript
复制
void insertString(Node** head_ref, char* str) {
    for (int i = 0; str[i] != '\0'; i++) {
        insertAtEnd(head_ref, str[i]);
    }
}

最后,你可以创建一个主函数来测试这些功能:

代码语言:javascript
复制
int main() {
    Node* head = NULL;
    char str[] = "Hello, World!";
    insertString(&head, str);
    
    // 打印链表内容
    Node* temp = head;
    while (temp != NULL) {
        printf("%c ", temp->data);
        temp = temp->next;
    }
    
    return 0;
}

这个程序会输出:H e l l o , W o r l d !

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券