當時是由於未知字符串個數而且要求以空行結束,用鏈表來實現比較合適。妳要是想改成輸入6個字符串也行,直接在Node *Create() 函數裏頭加個計數器,這樣也能省去空行結束的要求。或者不改,直接輸入6個字符串,然後連續2下回車就得到最大字符串。
當時定義字符串長度20,妳要是輸入字符串長度大於這個數,程序往下數第6行的char str[20]改壹下就行。
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct tagNode
{
char str[20];
struct tagNode *Next;
}Node;
Node *Create(); /* 創建鏈表 */
Node *ListSort(Node *); /* 排序 */
bool StringLenth( char * ); /* 是否空行 */
void Print(Node *); /* 輸出 */
int main(void)
{
Node *pHead;
pHead = Create();
pHead = ListSort( pHead );
Print( pHead );
return 0;
}
Node *Create()
{
Node *pHead, *pTemp, *pCurrent;
printf( "Input strings to creat a list,end with a blank line:\n" );
pTemp = ( Node * )malloc( sizeof(Node) );
if( pTemp == NULL )
printf( "malloc error! " );
pHead = pTemp;
gets( pTemp->str );
if( !StringLenth( pTemp->str ) ) /* 空行 */
return NULL;
while( StringLenth( pTemp->str ) ) /* 非空行 */
{
pCurrent = pTemp;
pTemp = ( Node * )malloc( sizeof(Node) );
if( pTemp == NULL )
{
printf( "malloc error! " );
break;
}
gets( pTemp->str );
pCurrent->Next = pTemp;
}
pCurrent->Next = NULL;
return pHead;
free ( pTemp );
}
Node *ListSort( Node *pHead )
{
Node *pCurrent, *pTemp, *pEnd, *pNext;
if( pHead == NULL )
return NULL;
if( pHead->Next == NULL )
return pHead;
pTemp = ( Node * )malloc( sizeof(Node) );
if( pTemp == NULL )
printf( "malloc error! " );
for(pEnd = pHead; pEnd->Next != NULL; pEnd=pEnd->Next)
{
for (pCurrent=pEnd, pNext=pCurrent->Next; pNext!=NULL; pNext=pNext->Next)
{
if( strcmp( pCurrent->str, pNext->str) < 0 )
{/*直接對節點內的字符串進行操作,沒有涉及節點指針*/
strcpy( pTemp->str, pNext->str );
strcpy( pNext->str, pCurrent->str );
strcpy( pCurrent->str, pTemp->str );
}
}
}
free ( pTemp );
return pHead;
}
bool StringLenth( char *p )/* 空行則長度為0,非空行則長度至少1 */
{
int count = 0;
while( *p != '\0')
{
count ++;
p++;
if( count > 0 ) /* 當長度計數為1時,可停止計數 */
break;
}
return (count==1?1:0); /* 空行返回0,非空行返回1 */
}
void Print( Node *pHead )
{
if( pHead == NULL )
printf( "The list is empty!\n" );
else printf( "The max string is %s\n", pHead->str );
}