字符串采用链式存储结构,设计求子串的算法;代码
时间: 2024-05-12 18:19:06 浏览: 77
专升本数据结构第五章 串.pdf
以下是一个求子串的算法,采用了链式存储结构。
```
// 定义链表节点结构体
typedef struct ListNode {
char data;
struct ListNode* next;
} ListNode;
// 定义链表结构体
typedef struct {
ListNode* head;
int length;
} LinkedList;
// 初始化链表
void initLinkedList(LinkedList* list) {
list->head = NULL;
list->length = 0;
}
// 在链表尾部插入元素
void insertNode(LinkedList* list, char data) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->data = data;
node->next = NULL;
if (list->head == NULL) {
list->head = node;
} else {
ListNode* p = list->head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
list->length++;
}
// 从链表中删除指定位置的节点
void deleteNode(LinkedList* list, int index) {
if (index < 0 || index >= list->length) {
return;
}
if (index == 0) {
ListNode* p = list->head;
list->head = p->next;
free(p);
} else {
ListNode* p = list->head;
for (int i = 0; i < index - 1; i++) {
p = p->next;
}
ListNode* q = p->next;
p->next = q->next;
free(q);
}
list->length--;
}
// 求子串
LinkedList* getSubString(LinkedList* list, int start, int end) {
if (start < 0 || start >= list->length || end < 0 || end >= list->length || start > end) {
return NULL;
}
LinkedList* subList = (LinkedList*)malloc(sizeof(LinkedList));
initLinkedList(subList);
ListNode* p = list->head;
for (int i = 0; i < start; i++) {
p = p->next;
}
for (int i = start; i <= end; i++) {
insertNode(subList, p->data);
p = p->next;
}
return subList;
}
```
使用示例:
```
int main() {
LinkedList list;
initLinkedList(&list);
insertNode(&list, 'a');
insertNode(&list, 'b');
insertNode(&list, 'c');
insertNode(&list, 'd');
insertNode(&list, 'e');
LinkedList* subList = getSubString(&list, 1, 3);
ListNode* p = subList->head;
while (p != NULL) {
printf("%c ", p->data);
p = p->next;
}
return 0;
}
```
输出结果:
```
b c d
```
阅读全文