首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求大神发威,把这几道也给做了吧!该如何处理

2013-01-04 
求大神发威,把这几道也给做了吧!求大神发威,把这几道也给做了吧[解决办法]写了第一题,有空再写别的吧/* *

求大神发威,把这几道也给做了吧!
求大神发威,把这几道也给做了吧!该如何处理

求大神发威,把这几道也给做了吧
[解决办法]
写了第一题,有空再写别的吧


/*
 * main.c
 *
 *  Created on: 2012-12-1
 *      Author: Administrator
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_LEN 32

void print(char ** str, int n){
FILE *f = fopen("out.txt", "w");
if(f == NULL)
return;
int i =0;
for(i = 0; i < n; ++i)
fprintf(f, "%s\n", str[i]);
fclose(f);
}

void qsort_str(char **str, int i, int j){
int l = i, r = j;
char * t;
if(l < r){
t = str[l];
while(l < r){
while(l < r && strcmp(str[r], t) >= 0)
r--;
str[l] = str[r];
while(l < r && strcmp(str[l],t) <= 0)
++l;
str[r] = str[l];
}
str[l] = t;
qsort_str(str, i, l -1);
qsort_str(str, l + 1, j);
}
}

int main(){
int i, n = 0;
printf("Input number of string : \n");
scanf("%d", &n);
printf("Input %d strings :\n", n);
char **str = (char **)malloc(sizeof(char *) * n );
for(i = 0; i < n; ++i)
str[i] =  (char *)malloc(MAX_LEN);
for( i = 0; i < n; ++i){
scanf("%s", str[i]);
}
qsort_str(str, 0, n-1);
print(str, n);
for(i = 0; i < n; ++i)
free(str[i]);
free(str);
return 0;
}


[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#defineMAX 30

typedefstruct strings{
char content[MAX];
struct strings * next;
}* pNode; 

pNode input(void);//取得输入
void string_sort(pNode);//排序


int main(void){
pNode head,current;//链表获取输入
pNode temp;
FILE * fp;


//打开文件
if((fp = fopen("file","w+")) == NULL){
fprintf(stdout,"Open file is failure!\n");
return 1;
}

printf("Enter strings(empty line to quit!):\n");

//获取输入
head = input();

//排序
string_sort(head);

//写入文件

current = head;

while(current != NULL){
fputs(current->content,fp);
current = current -> next;
}

//释放内存

current = head;

while(current != NULL){
temp = current->next;
free(current);
current = temp;
}

return 0;


}

pNode input(void){
pNode prev,current,head;
char buffer[MAX];

//初始化头指针
head = NULL;



//获取输入
while(fgets(buffer,MAX,stdin) != NULL && buffer[0] != '\n'){
current = (pNode)malloc(sizeof(struct strings));

if(head == NULL)head = current;
else prev->next = current;

strncpy(current->content,buffer,MAX);

prev = current;

current ->next = NULL;


}

//返回
return head;

}


void string_sort(pNode head){
int num = 0;//字串个数
pNode current;
int round,times;
char * * pa;
int i = 0;
char temp[MAX];

//取字串个数

current = head;

while(current != NULL){
num ++;

current = current ->next;
}


//存放字串首地址的数组
pa = (char * *)malloc(sizeof(char *) * num);


//取得字串
current = head;

while(current != NULL){
 pa[i++] = current ->content;
 current = current ->next;
}



//排序


for(round = 1;round < num;round ++)
for(times = 0;times < num - round;times ++){
if(strcmp(pa[times],pa[times+1])<0){
strcpy(temp,pa[times]);
strcpy(pa[times],pa[times+1]);
strcpy(pa[times+1],temp);
}

}

//释放pa
free(pa);



return;



}

热点排行