2009年5月26日 星期二

字串項目鍵入與排序 (c++)

//===============================================================
// 20090525/26 知識 +
// http://tw.knowledge.yahoo.com/question/question?qid=1609052600695
// http://tw.knowledge.yahoo.com/question/question?qid=1009052511472
// 發問者 :(菱ˇ角 ) http://tw.knowledge.yahoo.com/my/my?show=AA00054490
//===============================================================


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

class SortList
{
struct Node
{
char * Data;
Node * Next;
Node(char *data) // 建構式
{
Data = new char[strlen(data)+1];
strcpy(Data, data);
}
~Node() { delete [] Data; } // 解構式
} * _First;
int _len;
public:
SortList():_First(NULL),_len(0){} // 建構式
~SortList() { Clear(); } // 解構式
void Clear() // 全部清空
{
Node * node, *pre;
for(node = _First; node!=NULL; node=node->Next, delete pre)
pre = node;
_First = NULL;
_len=0;
}
void Add(char *data) // 增加項目
{
Node * node, * pre, * add = new Node(data);
for( node = _First; node!=NULL && strcmpi(data, node->Data)>0; node=node->Next)
pre = node;
if (node==_First)
{
add->Next = _First;
_First = add;
}
else
{
add->Next = pre->Next;
pre->Next = add;
}
_len++;
}
int Lenght() { return _len; } // 取得項目數量

const char * operator[](int num) // 多載成陣列項目
{
if (num>=_len) return NULL;
Node * node = _First;
for(int i=0; i<num && node!=NULL; i++) node=node->Next;
return node->Data;
}
};
// =========== 主程式
int main()
{
char name[16];
SortList list;
while(1)
{
cout<<"請輸入名字(按Enter結束輸入) : ";
cin.getline(name,sizeof(name));
if (strlen(name)==0) break;
list.Add(name);
}
int len = list.Lenght();
cout << endl << "排序中最前的名字 : " << list[0] << endl;
cout << endl << "排序中最後的名字 : " << list[len-1] << endl;
cout << endl << "顯示所有名字排序 --- "<< endl;
for(int i=0; i<len; i++)
cout << "[" << (i+1) << "] 名字 :" << list[i] << endl;
system("pause");
return 0;
}

//==========================================================


//==========================================================
這裡是另外一種寫法, 當資料的筆數有受限時....


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

const int LEN = 16; // 每筆大小
const int MAX = 200; // 限制最大筆數
int Sort[MAX]; // 資料索引排序
char Names[LEN*MAX]; // 存放資料

// =========== 主程式
int main()
{
int count, p, i, n;
for( count=0, p=0; count<MAX; count++, p+=LEN )
{
cout<< "請輸入第 " << (count+1) << "筆名字(按Enter結束輸入) : ";
cin.getline(Names+p, LEN);
if (strlen(Names+p)==0) break;
for(i=0; i<count; i++)
if (strcmpi(Names+p, Names+Sort[i])<0) break;
for(n=count; n>i; n--) Sort[n] = Sort[n-1];
Sort[i] = p;
}
cout << endl << "排列中最前(小)的名字 : " << Names+Sort[0] << endl;
cout << endl << "排列中最後(大)的名字 : " << Names+Sort[count-1] << endl;
cout << endl << "顯示所有名字排列 --- "<< endl;
for(int i=0; i<count; i++)
cout << "[" << (i+1) << "] 名字 : " << Names+Sort[i] << endl;
return 0;
}
//===============================================

沒有留言:

張貼留言