注册 登录
编程论坛 C++教室

C++链表插入问题

xianyun1994 发布于 2010-02-15 22:27, 525 次点击
程序代码:
源码如下 应该是在void search(spra *head)函数中出的问题 大虾指点下
#include <iostream>

using namespace std;

int NodeNumber = 0;
struct spra
{
     char name;
     spra *next;
};

spra *creat(int &number);//创建链表
void search(spra *head);
void show(spra *head);//遍历
int find(spra *head);

int main()
{
     spra *head;
     int number = 0;
     head = creat (number);
     cout <<"你输入的字符数是:" <<find(head) <<endl;
     show (head);
     search(head);
     show(head);
     return 0;
}

spra *creat(int &number) //创建链表
{
        spra *head = NULL;
     spra *pend = head;
     spra *ps;
     char temp;
     cout <<"请输入字符:"<<endl;
     do
     {
         cin >>temp;
         if (temp != '#')
         {
             ps = new   spra;
             ps->name = temp;
             ps->next = NULL;
             if (head == NULL)
             {
                 head = ps;
             }
             else
             {
                 pend->next = ps;
             }
             pend = ps;
             number++;
         }
     }while (temp != '#');
     return head;
}

void show (spra *head)   //遍历
{
     cout <<"你输入的字符如下:"<<endl;
     spra *te = head;
     while (te != NULL)
     {
         cout <<te->name;
         te = te->next;
     }
     cout <<endl;
}

void search(spra *head)
{
     spra *al = head;
     spra *NewNode = new spra;
     cout <<"->"<<endl;
     NewNode->name = '!';
     while (al != NULL)
     {
         if (al->name == 'a')
         {
             NewNode->next = al->next;
             al->next = NewNode;
             search(NewNode->next);
         }
         al = al->next;
     }
}

int find(spra *head)
{
     spra *s = head;
     while(s != NULL)
     {
         NodeNumber++;
         s = s->next;
     }
     return NodeNumber;
}
4 回复
#2
cnfarer2010-02-16 12:23
void search(spra *head)实现什么功能啊?
#3
THQatSEU2010-02-16 22:12
应该是在每个a的前面加上'!'
#4
cnfarer2010-02-17 14:16
这是用递归,当然也可以用循环!
void search(spra *head)
{
    if (head->name=='a')
    {
        spra *NewNode = new spra;
        NewNode->name='a';
        head->name='!';
        NewNode->next=head->next;
        head->next=NewNode;
        if (head->next->next)
        {
             search(head->next->next);
        }
    }
    else
         if (head->next)
         {
             search(head->next);
         }
}
#5
cnfarer2010-02-17 14:34
void search(spra *head)
{
     //cout <<"->"<<endl;
     spra *al = head;
     while (al != NULL)
     {
         if (al->name == 'a')
         {
             spra *NewNode = new spra;
             NewNode->name = 'a';
             al->name='!';
             NewNode->next = al->next;
             al->next = NewNode;
             al=NewNode->next;
         }
         else
         al = al->next;
     }
}
1