0
void alphaout()
 {
   nodealpha *curr;
   nodealpha *curr2;
   curr = first;
   curr2 = first;

while (curr != NULL)
 {
   char al1 = curr2 -> alpha;
   char al2 = curr -> alpha;
   if (al1 < al2)
    {
      curr2 = curr;
    }
 std::cout << "ALPHABET : " << curr -> alpha << endl;
 curr = curr -> next;
 }
}

我制作了一个简单的程序,用户输入每个字母,然后按顺序显示,不管用户输入字母的方式如何,但问题是当它显示时,字母的顺序与用户输入的顺序相同我不知道如何以 a 到 z 的方式排列它

4

2 回答 2

0

我可以想到两种不同的方法,第一种,您可以使用它们的 ascii 代码的索引将节点的地址保存在一个数组中:


// here is a function i made for an old project which will give you the index in an array 
//of any char you pass to it (sorry for spanish comments but that's my my teacher 
//asked for)
int position(char letter)
{
    int valor;
    //A-ascii 65 -> posicion 0  a-ascii 97 -> 0
    //Z-ascii 90 -> posicion 25  z->ascii 122 - 25
    if(letra>='A' && letra <='Z')
        valor = letra - 65;
    else if(letra >='a' && letra<='z')
        valor = letra-97;
    else
        valor= 26; //
    return valor;
}


// this is what i would put in your alphaout function to store the ponters
// here we save the pointers to each letter
nodealpha *alpha[size of your aplhabet];

while(curr != NULL){
    alpha[position(curr->alpha)] = curr;
    curr = curr->next;
}
// after this you can just print the array
cout << "alphabet: " << endl;
for(int i = 0; i < (size of alphabet); i++){
    cout << alpha[i]->alph << ", ";
} 

这样做的缺点是它不会考虑重复,它只会 dabe 每个字母的最后一个实例

至于另一种方法,您可以为字母表中的每个字母扫描一次列表并立即打印它,但这将花费更多时间来完成,但它会计算重复。

于 2020-05-20T04:36:58.450 回答
0

由于字符是由数字组成的ASCIIASCII所以我们可以先将char类型转换为int数组内部的类型,然后通过使用qsort()我们可以适当地重新排列它们。char然后在重新排列时将它们转换为新的。

以下代码是一个示例:

#include <iostream>      
#include <cstdlib>     
#include <string>
#include <vector>
#include <algorithm>

int main ()
{
   std::ios_base::sync_with_stdio(false);
   std::string order;

   std::cout << "Input the alphabet order: ";
   std::getline(std::cin, order);

   int Alphabet[26];
   std::string::iterator iter;
   for(iter = order.begin();iter != order.end(); iter++){
        Alphabet[order.find(*iter)] = *iter; 
   }

   qsort (Alphabet, order.length(), sizeof(int), [](const void* a, const void* b)->int{
       return (*(int*)a - *(int*)b );
   });

   std::vector<int> Filter;
   for(int x = 0; x < order.length(); x++){
      if(std::find(Filter.begin(), Filter.end(), Alphabet[x]) == Filter.end()){
        Filter.push_back(Alphabet[x]); // to filter out repetitive characters.
      }
   }

   std::vector<int>::iterator Iter;
   std::cout << "ALPHABET: ";
   for(Iter = Filter.begin(); Iter != Filter.end(); Iter++){
      std::cout << static_cast<char>(*Iter); 
   }
   std::cout << std::endl;

   return 0;

}
于 2020-05-20T04:47:56.717 回答