1.定义单链表head和字符串str。 2.初始化单链表。 3.编写串比较函数。 4.调用串插入,串删除模块实现串操作。
时间: 2023-05-20 15:02:48 浏览: 106
1. 定义单链表head和字符串str:
```c
typedef struct Node {
char data;
struct Node *next;
} Node;
Node *head = NULL;
char str[] = "Hello, world!";
```
2. 初始化单链表:
```c
void initList() {
head = (Node *)malloc(sizeof(Node));
head->next = NULL;
}
```
3. 编写串比较函数:
```c
int strCompare(char *s1, char *s2) {
while (*s1 && *s2 && (*s1 == *s2)) {
s1++;
s2++;
}
return *s1 - *s2;
}
```
4. 调用串插入,串删除模块实现串操作:
```c
void strInsert(char *s, int pos, char *t) {
int len = strlen(t);
Node *p = head;
for (int i = 0; i < pos && p; i++) {
p = p->next;
}
if (!p) {
return;
}
for (int i = 0; i < len; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = t[i];
newNode->next = p->next;
p->next = newNode;
p = p->next;
}
}
void strDelete(char *s, int pos, int len) {
Node *p = head;
for (int i = 0; i < pos && p; i++) {
p = p->next;
}
if (!p) {
return;
}
for (int i = 0; i < len && p->next; i++) {
Node *temp = p->next;
p->next = temp->next;
free(temp);
}
}
```
阅读全文