输入一行字符建立字符链表,输入一个字符,查找该字符在链表中的位置序号表示,程序应考虑查找失败的情况

要用大一学到的指针,字符链表,数组等,谢谢!
2024-11-22 23:09:37
推荐回答(1个)
回答1:

#include
#include

typedef struct cha {
char ch;
struct cha *next;
}*CH;

CH CreatLink(char *s) {
char *cpt = s;
CH head,p,q;
head = p = (CH)malloc(sizeof(cha));
while(*cpt++) {
q = (CH)malloc(sizeof(cha));
q->ch = *cpt;
p->next = q;
p = q;
}
p->next = NULL;
return head;

}

int FindLink(CH head,char c) {
int n = 1;
CH p = head->next;
while(p != NULL) {
if(p->ch == c) return n;
++n;
p = p->next;
}
return -1;

}

void DispLink(CH head) {
CH p = head->next;
while(p != NULL) {
printf("%c ",p->ch);
p = p->next;
}
printf("\n");
}

void FreeLink(CH head) {
CH p,q;
p = head;
q = p->next;
while(q != NULL) {
p = q;
q = p->next;
free(p);
}
free(head);

}

int main() {
CH head;
char s[80],c;
int n;
printf("请输入一个字符串 : ");
gets(s);
head = CreatLink(s);
DispLink(head);
printf("请输入要查找的字符 : ");
c = getchar();
n = FindLink(head,c);
if(n > 0) printf("找打了。字符%c在链表中的序号是:%d。\n",c,n);
else printf("没有找到字符'%c'。\n",c);
system("pause");
return 0;

}