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

时间:2023-03-09 20:09:16
字符单链表识别数字,字母,其它字符,并分为三个循环链表的算法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;

}

运行结果截图:

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

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