匆忙实现,有时间再优化总结。
第一次修改:增加排序段代码,head作为头结点不存储数据。
目前仍然存在的问题:最后一个数字和结束符(Q或者q之间如果没有空格的话不会识别),有时间再改
/*************************************************************************************
程序功能:从键盘输入数字,以空格或换行作为结束,排序后输出。输入的数字
个数不定,使用链表实现
*************************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 10
struct Node
{
long value;
struct Node* next;
};
struct Node* getNum();
void sortNode(struct Node *head);
int main()
{
struct Node* head;
struct Node *node, *next;
head = NULL;
node = NULL;
printf("please input some num. input Q / q to quit:\n");
//输入字符或数字
head = getNum();
head->value = -1;
//排序
sortNode(head->next);
//输出
node = head->next;
while(node != NULL){
printf("the num is:%ld\t", node->value);
node = node->next;
}
printf("\n");
//释放
node = head->next;
free(head);
while(node != NULL){
printf("free the num:%ld\t", node->value);
next = node->next;
free(node);
node = next;
}
printf("\n");
getchar();
getchar();
return 0;
}
struct Node* getNum()
{
char str[MAXSIZE+1];
struct Node *head, * p1, * p2;
long num;
head = (struct Node*)malloc(sizeof(struct Node));
if(NULL == head){
printf("memory allocate failed...\n");
return head;
}
p1 = p2 = head;
scanf("%s", str);
while((strcmp(str, "Q") != 0) && (strcmp(str, "q") != 0)){
num = strtol(str, 0, 0);
printf("input num is:%ld\n", num);
p2 = p1;
p1 = (struct Node*)malloc(sizeof(struct Node));
if(p1 == NULL){
printf("memory allocate failed...\n");
return head;
}
p1->value = num;
p1->next = NULL;
p2->next = p1;
scanf("%s", str);
}
printf("END...\n");
return head;
}
void sortNode(struct Node *head)
{
struct Node *p1, *p2;
long tempValue;
p1 = p2 = NULL;
p1 = head;
while(NULL != p1)
{
p2 = p1->next;
while(NULL != p2)
{
if (p1->value < p2->value)
{
//交换
tempValue = p1->value;
p1->value = p2->value;
p2->value = tempValue;
}
p2 = p2->next;
}
p1 = p1->next;
}
}