题解 | 找位置

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct IndexNode{
    int index;
    struct IndexNode*next;
}IndexNode;
typedef struct CharNode{
    char a;
    IndexNode*start;
    struct CharNode*next;
}CharNode;

void Insert(CharNode*first,char element,int index);
void PrintLinkList(CharNode*first);
int main(){
    char str[101];
    for(int i=0;i<101;i++){
        str[i]=0;
    }
    scanf("%s",str);
    CharNode*first=(CharNode*)malloc(sizeof(CharNode));
    first->next=NULL;
    for(int i=0;i<strlen(str);i++){
        Insert(first,str[i],i);
    }
    PrintLinkList(first);
}

void Insert(CharNode*first,char element,int index){
    while(first->next){
        if(first->next->a==element){
            IndexNode*s=first->next->start;
            while(s->next){
                s=s->next;
            }
            s->next=(IndexNode*)malloc(sizeof(IndexNode));
            s->next->index=index;
            s->next->next=NULL;
            return;
        }
        first=first->next;
    }
    first->next=(CharNode*)malloc(sizeof(CharNode));
    first->next->a=element;
    first->next->start=(IndexNode*)malloc(sizeof(IndexNode));
    first->next->next=NULL;
    first->next->start->index=index;
    first->next->start->next=NULL;
}
void PrintLinkList(CharNode*first){
    CharNode*Iterator=first->next;
    while(Iterator){
       if(Iterator->start->next){
            IndexNode*Iterator2=Iterator->start;
            while(Iterator2->next){
                printf("%c:%d,",Iterator->a,Iterator2->index);
                Iterator2=Iterator2->next;
            }
            printf("%c:%d\n",Iterator->a,Iterator2->index);
       }
        Iterator=Iterator->next;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务