试编写C程序,建立相应字符串存储结构,从键盘接受字符输入建立块链串存储结构,并完成在指定位置插入某个子串,在指定位置删除指定长度子串的操作,并打印输出相应操作的结果。
时间: 2024-10-21 22:12:06 浏览: 26
在C语言中,我们可以创建一个简单的字符串链表结构来实现这个功能。首先,我们需要定义一个节点结构体,包含字符和指向下一个节点的指针:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义链表节点结构
typedef struct Node {
char data;
struct Node* next;
} Node;
// 创建链表头结点
Node* createList() {
return (Node*)malloc(sizeof(Node));
}
// 插入节点到链表
void insertNode(Node** head, char data, int pos) {
Node* newNode = createList();
newNode->data = data;
newNode->next = *head;
if (pos == 0) {
*head = newNode;
} else {
Node* current = *head;
for (int i = 0; i < pos - 1 && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
}
}
}
// 删除指定位置的子串
void deleteSubstring(Node** head, int start, int length) {
if (*head == NULL || start + length > strlen(*head->data)) {
return;
}
Node* prev = NULL;
Node* curr = *head;
for (int i = 0; i < start; i++) {
curr = curr->next;
}
// 如果start位置在链表开始,直接删除
if (curr == *head) {
*head = curr->next;
} else {
while (length > 0) {
prev->next = curr->next;
curr = curr->next;
length--;
}
}
}
// 打印链表内容
void printList(Node* head) {
while (head != NULL) {
printf("%c", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node* head = createList();
char input[100];
int position, subLength;
printf("Enter characters to build the string: ");
fgets(input, sizeof(input), stdin); // 获取用户输入
input[strcspn(input, "\n")] = '\0'; // 移除换行符
// 将输入的字符插入到链表中
for (char c : input) {
insertNode(&head, c, 0);
}
// 询问用户操作
printf("Enter operation:\n1. Insert at position\n2. Delete substring\nYour choice: ");
scanf("%d", &position);
if (position == 1) {
printf("Enter character to insert and position: ");
getchar(); // 清除前一个输入的回车
scanf(" %c%d", &input[0], &position);
insertNode(&head, input[0], position);
} else if (position == 2) {
printf("Enter start position and length of substring to delete: ");
scanf(" %d%d", &start, &subLength);
deleteSubstring(&head, start, subLength);
}
// 打印操作后的链表
printf("After operation: \n");
printList(head);
return 0;
}
```
阅读全文