• 字符单链表识别数字,字母,其它字符,并分为三个循环链表的算法c++实现


    已知一个单链表中的数据元素含有三类字符(即字母字符,数字字符和其它字符),试编写算法,构造三个循环链表,使每个循环链表中只含有同一类的字符,且利用原表中的结点空间作为这三个表的结点空间。

    实现源代码:

    #include<iostream>

    #include<stdio.h>

    #include<string.h>

    using namespace std;

    struct node

    {

        char ch;

        node*link;

    };

    //为了方便输出,定义一个输出字符的函数,适用于单链表

    void printlist(node*h)

    {

        node *first=h;

        while(first!=NULL)

        {

            cout<<first->ch;

            first=first->link;

        }

    }

    void printcirclelist(node*p)

    {

        node *first=p;

        while(true)

        {

            cout<<first->ch;

            first=first->link;

            if(first==p)break;

        }

    }

    bool is_num(char c)

    {

        if(c>='0'&&c<='9')return true;

        else return false;

    }

    bool is_eng(char c)

    {

        if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))return true;

        else return false;

    }

    bool is_else(char c)

    {

        if(!is_num(c)&&!is_eng(c))return true;

        else return false;

    }

    int main()

    {

        //下面构造一个字符单链表

        node *list_head=new node();

        node *p=list_head;

        char ch[100]="235543kj45i##%GGG%%&&hd7&&&";

        for(int i=0;i<27;i++)

        {

            if(i!=0)

            {

                p->link=new node();

                p=p->link;

            }

            p->ch=ch[i];

        }

        p=NULL;

        printlist(list_head);

        //数字循环链表

        node*head1=new node();

        //字母循环链表

        node*head2=new node();

        //其它字符循环链表

        node*head3=new node();

        //下面从"235543kj45i##%GGG%%&&hd7&&&"中提取数字,字母和其他字符

        node *pointer=list_head;

        node*p1=head1;

        node*p2=head2;

        node*p3=head3;

        while(pointer!=NULL)

        {

            if(is_num(pointer->ch)){p1->link=pointer;p1=p1->link;}

            if(is_eng(pointer->ch)){p2->link=pointer;p2=p2->link;}

            if(is_else(pointer->ch)){p3->link=pointer;p3=p3->link;}

            pointer=pointer->link;

        }

        //下面将进行首尾相接

        p1->link=head1;

        p2->link=head2;

        p3->link=head3;

        //至此循环链表建立完成

        cout<<endl;

        printcirclelist(head1);

        cout<<endl;

        printcirclelist(head2);

        cout<<endl;

        printcirclelist(head3);

        return 0;

    }

    运行结果截图:

    (可见该算法可以将三种不同的字符识别出来并构造循环链表)

  • 相关阅读:
    Java集合容器面试题(2022最新版)
    消息中间件MQ与RabbitMQ面试题(2022最新版)
    Spring面试题(2022最新版)
    程序员何苦为难程序员!
    HashMap的remove树节点的时候树会进行退化
    Spring Boot面试题(2022最新版)
    Spring MVC面试题(2022最新版)
    Redis面试题(2022最新版)
    Java虚拟机(JVM)面试题(2022最新版)
    那些游戏告诉我们,这就是人生!
  • 原文地址:https://www.cnblogs.com/linruier/p/9485217.html
Copyright © 2020-2023  润新知