单链表拆分
设单链表中仅有三类字符的数据元素(大写、数字、其他字符),要求利用原单链表中结点空间设计出三个单链表的算法,使每个单链表只包含同类字符。
- 算法思想
//情况 若当前结点的数据域为数字
//判断digital是否为空,若为空直接指向p 设置临时结点q 指向p p向后移动,将p头插法插入结点
void Diversion(LNode *L){
LNode *p=L->next,*digtal=0,*al=0,*other=0;
L->next=0;
LNode *q;
while(p){
if(p->data>='0'&&p->data<='9'){
if(!digtal){
digtal=p;
p=p->next;
digtal->next=0;
}
else {
q=p;
p=p->next;
q->next=digtal->next;
digtal->next=q;
printf(" ");
}
}
else if(p->data>='A'&&p->data<='Z'){
if(!al){
al=p;
p=p->next;
al->next=0;
}
else {
q=p;
p=p->next;
q->next=al->next;
al->next=q;
}
}
else {
if(!other){
other=p;
p=p->next;
other->next=0;
}
else {
q=p;
p=p->next;
q->next=other->next;
other->next=q;
}
}
}
printf("\n");
while(digtal) {
digtal=digtal->next;
}
printf("\n");
while(al) {
printf("大写字母 :%c \n ",al->data);
al=al->next;
}
printf("\n");
while(other) {
printf("其他 :%c \n",other->data);
other=other->next;
}
}
int main(){
LNode *L=HeadCreateList(10);
//int count=Count(L,3);
LNode *p=L->next;
Diversion(L);
}
- 运行结果