Poj 1002 487-3279(二叉搜索树)

题目链接:http://poj.org/problem?id=1002

思路分析先对输入字符进行处理,转换为标准形式;插入标准形式的电话号码到查找树中,若有相同号码计数器增加1,再中序遍历查找树。

 

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct TreeNode;
typedef char ElementType[30];
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
struct TreeNode
{
    int Count;
    ElementType Element;
    SearchTree Left;
    SearchTree Right;
};

void StrToNum( char *str , char * Tel );
SearchTree MakeEmpty( SearchTree T );
SearchTree Insert( ElementType X, SearchTree T );
void PrintTel( SearchTree T );
int flag = 0;

int main()
{
    int n;
    char Str[100], Tel[100];
    SearchTree T = NULL;

    menset( Tel, 0, sizeof(Tel) );

    scanf( "%d", &n );
    for ( int i = 0; i < n; ++i )
    {
        scanf( "%s", Str );
        StrToNum( Str, Tel );
        T = Insert( Tel, T );
    }

    PrintTel( T );
    if ( flag == 0 )
        printf( "No duplicates.\n" );

    return 0;
}


void PrintTel( SearchTree T )
{
    if ( T != NULL )
    {
        PrintTel( T->Left );
        if ( T->Count > 1 )
        {
            printf( "%s %d\n", T->Element, T->Count );
            flag = 1;
        }
        PrintTel( T->Right );
    }
}


SearchTree MakeEmpty( SearchTree T )
{
    if ( T != NULL )
    {
        MakeEmpty( T->Left );
        MakeEmpty( T->Right );
        free( T );
    }
    return NULL;
}


SearchTree Insert( ElementType X, SearchTree T )
{    
    if ( T == NULL )
    {
        T = ( Position )malloc( sizeof( struct TreeNode ) );
        if ( T == NULL )
        {
            printf( "Out of space" );
            return NULL;
        }
        else
        {
            strcpy( T->Element, X );
            T->Left = T->Right = NULL;
        }
    }
    else
    if ( strcmp(X, T->Element) < 0 )
        T->Left = Insert( X, T->Left );
    else
    if ( strcmp(X, T->Element) > 0 )
        T->Right = Insert( X, T->Right);

    return T;   
}

void StrToNum( char *str , char * Tel )
{
    int i, j;

    for ( i = j = 0; str[i] != '\0'; i++ )
    {
        if ( str[i] == '-' );
        else
        if ( '0' <= str[i] && str[i] <= '9' )
            Tel[j++] = str[i];
        else 
        if ( str[i] < 'Q' )
            Tel[j++] = ( str[i] - 'A' ) / 3 + 2 + '0';
        else
            Tel[j++] = ( str[i] - 'A' - 1 ) / 3 + 2 + '0';

        if ( j == 3 )
            Tel[j++] = '-';
    }
}

 

转载于:https://www.cnblogs.com/tallisHe/p/4007894.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值