【编程语言】C++--华为面试题

来源:互联网 发布:移动免流端口 编辑:程序博客网 时间:2024/06/06 17:53

任意一串字符串 字符串里包含数字部分和一般的字符

例如 ad2ef35adx1wewe76
注意这个字符串 里面有4个数字 分别是 1 2 35 76  不考虑大数

将数字按照从小到大排序 组成一个新的字符串

要求制作一个函数来进行处理

 

我的解决办法 C++实现

#include <iostream>
#include <string>
using namespace std;

struct Node
{
 int nItem;
 Node * pNext;
};

class Linklist
{
private:
 Node * pFirst;
public:
 Linklist();
    void insertItem(int nItem);
 int getLength();
 Node *getPFirst();

 
};

Linklist::Linklist()
{
 
 pFirst = new Node;
 pFirst->nItem = 0;
 pFirst->pNext = NULL;
}
int Linklist::getLength()
{
 
 int nCount = 0;
 Node *pfirst = new Node;
 pfirst = pFirst;
 while(pfirst->pNext != NULL)
 {
  nCount ++;
  pfirst = pfirst->pNext;
 }
 
 return nCount;
 
 
}
void Linklist::insertItem(int nItem)
{
 
 Node *pNew = new Node;
 pNew->nItem = nItem;
 Node *pPre = pFirst;
 Node *pfirst = pFirst;
 if(pfirst->pNext == NULL)
 {
  
  pfirst->pNext = pNew;
  pNew->pNext = NULL;
 }
 else
 {
  pfirst = pfirst->pNext;
  
  while (pfirst->nItem <= pNew->nItem && pfirst->pNext != NULL)
  {
   pPre = pfirst;
   pfirst = pfirst->pNext;
   
  }
  
  if(pfirst->pNext == NULL && pfirst->nItem <= pNew->nItem)
  {
   pfirst->pNext = pNew;
   pNew->pNext = NULL;
  }
  else
  {
   
   pPre->pNext = pNew;
   pNew->pNext = pfirst;
   
  }
 }


 
}

Node *Linklist::getPFirst()
{
 return pFirst;
}

int main()
{
 Linklist list;
 string str;
 getline(cin,str);
 cout << "the string input is:"<< str << endl;
 int i = 0;
 char c;
 while(i < str.size())
 {
    c = str[i];
      int nC = c - '0';
   if(nC >= 1 && nC <= 9)
   {
        list.insertItem(nC);
   
   }
   
    i ++;

 
 }
    Node * p = list.getPFirst();
 if(list.getLength() != 0)
 {
  p = p->pNext;
 while(p->pNext != NULL)
 {
  cout<<p->nItem<<endl;
  p = p->pNext;
  
 }
 cout<<p->nItem<<endl;
 }

 else
 {
  cout<<"no signal"<<endl;
 }
 
 return 0;
}

 

原创粉丝点击