怎么比较链表里的字符串和链表外的字符串
时间: 2023-11-27 09:28:32 浏览: 28
你可以使用两个指针,一个指针遍历链表内的字符串,一个指针遍历链表外的字符串。每次比较两个指针指向的字符,如果相同则继续向后遍历,如果不同则说明链表内的字符串与链表外的字符串不同,可以直接返回 false。当链表内的字符串比较完毕,且链表外的字符串也比较完毕时,则说明链表内的字符串与链表外的字符串相同,可以返回 true。
相关问题
c语言链表输入字符串
以下是一个示例,演示了如何在C语言中使用链表输入字符串:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义链表节点结构
struct Node {
char data[100];
struct Node* next;
};
// 在链表末尾插入节点
void insert(struct Node** head, char* data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
strcpy(newNode->data, data);
newNode->next = NULL;
// 如果链表为空,将新节点设置为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 找到链表末尾的节点
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
// 将新节点插入到末尾
current->next = newNode;
}
// 打印链表中的所有字符串
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%s ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 输入字符串并插入链表
char input[100];
printf("请输入字符串(输入exit结束):\n"); while (1) {
scanf("%s", input);
if (strcmp(input, "exit") == 0) {
break;
}
insert(&head, input);
}
// 打印链表中的所有字符串
printf("链表中的字符串为:\n");
printList(head);
return 0;
}
```
c语言链表传字符串例子
以下是一个简单的 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` 函数打印链表中的字符串。