少量字符串排序去重

一.题目:从键盘输入一个字符串,按照字符顺序从小到大进行排序,并要求删除重复字符。

   比如输入”ad2f3adjfeainzzzv”,则输出”23adefijnvz”

今天突然看到这样一个题目 就手痒起来,顺便练习一下 ,长期考虑业务问题,轻松一下

基本思路

1,键盘输入字符串,使用动态分配空间

2,将键盘输入的内容 对链表生成排序同时 进行

3,打印链表输出结果

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <syslog.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>

typedef struct data{
	
	char ch;
	struct data *next;
}t_Data;



void *
safe_malloc(int size)
{
    void *retval = NULL;
    retval = malloc(size);
    if (!retval) {
        printf("Failed to malloc %d bytes of memory: %s.  Bailing out", size, strerror(errno));
        exit(1);
    }
    memset(retval, 0, size);
    return (retval);
}

t_Data * add_node( t_Data *head,t_Data *node )
{
	t_Data *p=head;
    if( head==NULL ) {		
        printf("head is null\n");
        return NULL;
    }
	if ( node->ch < head->ch ){
		node->next=head;
		return node;
	}else if (node->ch > head->ch ){
			while(p->next != NULL){
				if ( node->ch == p->ch || node->ch == p->next->ch ){
					free(node);
					node=NULL;
					return head;
				}
				if ( node->ch > p->ch     && node->ch < p->next->ch ){
					node->next = p->next;
					p->next=node;
					return head;
				}
				p=p->next;
			}		
			node->next=NULL;
			p->next=node;		
	}else{
		free(node);
		node=NULL;
		return head;
	}
		
	return head;
		
}


int main(void)
{
    char *pString; //字符串指针
    int length;  //字符串实际长度
	t_Data *pmem;
	t_Data *head_pmem;
	t_Data *cp_head_pmem;
	t_Data *pf;
    char *p=pString;
    printf("Please input string :\n");
    scanf("%s",pString); //输入字符串
    length = strlen(pString);//获取字符串长
	char node_flag=0;
	while(*p!='\0'){
		pmem=(t_Data *)safe_malloc(sizeof(t_Data));
		if (node_flag==0){  
		    pmem->ch=*p;pmem->next=NULL;
                    head_pmem=pmem;
			cp_head_pmem=head_pmem;
			node_flag=1;
		}else{
			pmem->ch = *p;
                        pmem->next = NULL;
			head_pmem=add_node(cp_head_pmem,pmem);

			cp_head_pmem=head_pmem;
		}
	    p++;

	}
	pf=head_pmem;
	while ( pf !=NULL ){
		printf("%c--->",pf->ch);
		pf=pf->next;
	}

    return 0;	
}

 

找到了一个非常精简的代码,思路非常值得学习。很赞的编程思想实现,赏心悦目,不服气不行!!!,

评论区留下你的杰作吧。

#include<stdio.h>
#include"string.h"
int main(void)
{
    char str1[500]={0},str2[256]={0};
    int i;
    gets(str1);
    for(i=0;str1[i];i++)
    {
        str2[str1[i]]=1;
    }
    for(i=0;i!=256;i++)
        if(str2[i]==1)
            printf("%c",i);
    putchar('\n');
    return 0;
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值