单链表拆分

来源:互联网 发布:js怎么产生随机数 编辑:程序博客网 时间:2024/05/18 20:08

已知单链表中的元素含有三类字符:字母,数字和其它字符。试编写算法,构造三个循环链表,使每个循环链表中只含有同一类字符。

#include <iostream>#include<list>using namespace std;template <class T>struct Node{    T data;    Node<T>* next;};template <class T>//尾插建立循环单链表Node<T>* creat_back( Node<T> * first,int len){    Node<T>* r=first;    for( int i=0; i<len; i++)    {        int data;        cin>>data;        Node<T>* pnew=new Node<T>;        pnew->data=data;        pnew->next=r->next;        r->next=pnew;        r=pnew;    }    r->next=NULL;    return first;}template <class T>Node<T>* add_back(Node<T>* first,int x){    Node<T>* newnode=new Node<T>;    newnode->data=x;    newnode->next=NULL;    Node<T>* r=first;    while(r->next)        r=r->next;    r->next=newnode;    return first;}template <class T>//输出链表void show(Node<T>* first){    Node<T>* p=first->next;    while(p!=NULL)    {        cout<<p->data<<' ';        p=p->next;    }    cout<<endl<<endl;}template <class T>//输出链表循环单链表void show_cirlist(Node<T>* first){    Node<T>* p=first->next;    while(p!=first)    {        cout<<p->data<<' ';        p=p->next;    }    cout<<endl<<endl;}template<class T>void Ajust(Node<T>** A, Node<char>** D,Node<char>** B ){    *D=new Node<char>;    (*D)->next=*D;    *B=new Node<char>;    (*B)->next=*B;    Node<T>* p=*A;    Node<T>* q=p->next;    while(q!=NULL)    {        if((q->data<='z'&&q->data>='a')||(q->data>='A'&&q->data<='Z'))        {            p->next=q->next;            q->next=(*B)->next;            (*B)->next=q;        }        else if(q->data>='0'&&q->data<='9')        {             p->next=q->next;            q->next=(*D)->next;            (*D)->next=q;        }        else            p=q;        q=p->next;    }    p->next=*A;}int main(){    Node<char>* first=new Node<char>;    first->next=NULL;    for( int i=0;i<3;i++)    {        first=add_back(first,'a'+i);        first=add_back(first,'0'+i);        first=add_back(first,'-');    }    show(first);    Node<char>* str;    Node<char>* arr;    Ajust(&first,&arr,&str);    show_cirlist(first);    show_cirlist(arr);    show_cirlist(str);    return 0;}