链表

匆忙实现,有时间再优化总结。

第一次修改:增加排序段代码,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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值