少量字符串排序去重

一.題目:從鍵盤輸入一個字符串,按照字符順序從小到大進行排序,並要求刪除重複字符。

   比如輸入”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;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章