C++入门练习 76题(7)

来源:互联网 发布:哪种论坛源码比较好 编辑:程序博客网 时间:2024/06/03 16:21

  7. 读入一行文本,包含若干个单词(以空格间隔,%结尾)。将其中以 A 开头的
  单词与以 N 结尾的单词,用头尾交换的办法予以置换。

写了一个, 不过比较仓促,代码比较糟糕 :)  你能看得懂吗? 估计过一会我自己都看不懂了

 

#include <iostream>
using namespace std;

#define SIZE 200

char buf[SIZE] = "Who Are yoU Why are you here ruN Away! %";

//- 我的C语言流毒太深, 干什么事情都要想着用链表来做 :)
//- 等下次再想用标准C++的模板等写程序吧
typedef struct  word{
  
char *data;
  word 
*next;
}
word_t;

typedef 
struct wordlist
{
  word 
* head;
}
 wordlist_t;

bool input_with_percent();
void seperate_word();
void seperate_word(wordlist_t* list);
void insert_list(wordlist_t* list, word_t *insert_word);
void display_word(wordlist_t* list);
void delete_list(wordlist_t* list);

int main()
{

  
while(!input_with_percent())
  
{
    cout
<<"Please input a string, with % to terminate it."<<endl;
  }


  wordlist_t 
*thelist = (wordlist_t *)malloc(sizeof(wordlist_t));   // create list, C 语言模式的
  thelist->head = NULL;

  seperate_word(thelist);

  display_word(thelist);

  delete_list(thelist);

  free(thelist);

  system(
"PAUSE");
}



bool input_with_percent()
{
  cin.getline(buf, SIZE);
  
  
if(buf[strlen(buf)-1]=='%')
    
return true ;
  
else
    
return false;
}


void seperate_word(wordlist_t* list)
{
  unsigned 
int curPos = 0;
  unsigned 
int strtPos = 0;
  
char *tmp_str = strdup(buf);
  
char *fornext=tmp_str;
  word_t 
*tmp_word=NULL;
  
  
while(curPos < strlen(buf))
  
{
    
if(buf[curPos] == ' '|| buf[curPos] == '%')
    
{
      tmp_str[curPos] 
= 0;
      
if(strlen(fornext) > 0 )
      
{
        tmp_word 
= (word_t *)malloc(sizeof(word_t));
        tmp_word
->data = strdup(fornext);
        tmp_word
->next = NULL;
        
/////////////////////////////////////////////////////////
        
///// 如果为开头是A 结尾是N, 则交换这个单词

        if(tmp_word->data[0]=='A' || tmp_word->data[strlen(fornext)-1== 'N')
        
{
          
for(unsigned int i=0; i<strlen(tmp_word->data);i++)
            tmp_word
->data[i] = fornext[strlen(fornext)-1-i];
        }

        
////////////////////////////////////
        insert_list(list, tmp_word);
      }

      fornext 
= tmp_str+curPos+1;
    }

    curPos
++;
  }

  free(tmp_str);
}


void insert_list(wordlist_t* list, word_t *insert_word)
{
   word_t 
*tmp = list->head;
   
if(tmp == NULL)
   
{
     list
->head = insert_word;
     
return;
   }


  
while(tmp->next!=NULL)
    tmp 
= tmp->next;

  tmp
->next = insert_word;
}


void display_word(wordlist_t* list)
{
  word_t 
*theword=list->head;
  
while(theword!=NULL)
  
{
    cout
<<theword->data<<" ";
    theword 
= theword->next;
  }

  cout
<<endl;
}


void delete_list(wordlist_t* list)
{
  word_t 
*tmp1, *tmp2;
  tmp1
=list->head;
  
while (tmp1!=NULL)
  
{
    free(tmp1
->data);
     tmp2
=tmp1;
        tmp1
=tmp1->next;
    free(tmp2);
  }

}