假设以单链表结构表示串每个结点数据域存放一个字符且附设头结点。试用c语言编写算法实现串的下列基本操作StrAsignSchars;StrCopyST;StrCompareST;StrLengthS;StrCatST;SubStringSubSposlen
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
typedef struct Node {
char data;
struct Node *next;
} Node, *LinkedList;
void StrAssign(LinkedList S, char *chars) {
int i = 0;
Node *p = S;
while (chars[i] != '\0') {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = chars[i++];
newNode->next = NULL;
p->next = newNode;
p = newNode;
}
}
void StrCopy(LinkedList S, LinkedList T) {
Node *p = S->next;
Node *q = T->next;
while (p != NULL) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = p->data;
newNode->next = NULL;
q->next = newNode;
q = newNode;
p = p->next;
}
}
int StrCompare(LinkedList S, LinkedList T) {
Node *p = S->next;
Node *q = T->next;
while (p != NULL && q != NULL) {
if (p->data != q->data) {
return p->data - q->data;
}
p = p->next;
q = q->next;
}
return p == NULL ? -1 : 1;
}
int StrLength(LinkedList S) {
int len = 0;
Node *p = S->next;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
void StrCat(LinkedList S, LinkedList T) {
Node *p = S;
while (p->next != NULL) {
p = p->next;
}
Node *q = T->next;
while (q != NULL) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = q->data;
newNode->next = NULL;
p->next = newNode;
p = newNode;
q = q->next;
}
}
void SubString(LinkedList Sub, LinkedList S, int pos, int len) {
int i = 1;
Node *p = S->next;
while (p != NULL && i < pos) {
p = p->next;
i++;
}
Node *q = Sub;
while (p != NULL && i <= pos + len - 1) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = p->data;
newNode->next = NULL;
q->next = newNode;
q = newNode;
p = p->next;
i++;
}
}
int main() {
LinkedList S = (LinkedList) malloc(sizeof(Node));
S->next = NULL;
StrAssign(S, "hello");
printf("S: ");
Node *p = S->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\n");
LinkedList T = (LinkedList) malloc(sizeof(Node));
T->next = NULL;
StrCopy(S, T);
printf("T: ");
p = T->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\n");
printf("S compare T: %d\n", StrCompare(S, T));
printf("S length: %d\n", StrLength(S));
StrCat(S, T);
printf("S cat T: ");
p = S->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\n");
LinkedList Sub = (LinkedList) malloc(sizeof(Node));
Sub->next = NULL;
SubString(Sub, S, 2, 4);
printf("Sub: ");
p = Sub->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\n");
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/fHmp 著作权归作者所有。请勿转载和采集!