2024级超星程设C语言,排序单列表,实验09动态数据组织

题目编号:Exp09-Enhance04,GJBook3例-13-02

题目名称:排序单链表

题目描述:请填写缺失代码完成程序,实现如下功能:

    首先根据键盘随机输入一行以0结束的若干非零整数建立单链表;

    然后递增排序链表;

    最后验证输出排序后链表中所有值,相邻数字间以一个西文空格间隔,最后一个数字后无任何字符。

    若是空链表,则输出NULL。

例如,

    输入:2 3 6 4 5 0 

    输出:2 3 4 5 6

    输入:0 2 3 4 

    输出:NULL

***注意***:

    提交答案时,需粘贴完整的源代码,仅粘贴填空处的代码将被判错。

#include <stdio.h>
	#include <malloc.h>
	struct cell {//单链表结点结构体定义
	 int x;
	 struct cell* next;
	};
struct cell* build(void) {//新建单链表,并将建好的单链表首结点地址返回
	 struct cell* head, * temp, * p;
	 head=temp=p=NULL;
	 int n;
	 while(scanf("%d",&n)==1 && n!=0){
        temp=(struct cell *)malloc(sizeof(struct cell));
        temp->x=n;
        if(head==NULL){
            head=temp;
            head->next=NULL;
            p=head;
        }else{
            p->next=temp;
            temp->next=NULL;
            p=temp;
        }
	 }
	 return head;//返回单链表头
	}
	struct cell * sort(struct cell* head) {//递增排序链表,head是单链表首结点指针
	 struct cell* p, * p0, * r, * r0, * q;
	 p = p0 = r = r0 = q = NULL;
	 p = head;
	 //题上给的这种变量名我真的是用不习惯,用完感觉眼得瞎
	 if(head==NULL) return NULL;
	 if(head->next==NULL) return head;
	 struct cell * current=head,*forward=head;

	 while(current->next!=NULL){
        forward=current->next;
        while(forward!=NULL){

            if(current->x > forward->x){
                struct cell temp=*forward;
                *forward=*current;
                *current=temp;

                struct cell *temnext=forward->next;
                forward->next=current->next;
                current->next=temnext;
            }
         forward=forward->next;
        }
     current=current->next;
	}
	 return head;
	}   /*  sort */


	void print(struct cell* head) {//打印整个单链表,head是单链表首结点指针
	 struct cell * current=head;
	 if(current==NULL) return;
	 printf("%d",current->x);
	 while(current->next!=NULL){
        current=current->next;
        printf(" %d",current->x);
	 }
	}
	void release(struct cell* head) {//释放单链表空间,head是单链表首结点指针
	 if (head!=NULL) return;
	 struct cell * current=head,*prve=head;
	 while(current!=NULL){
         prve=current->next;
         free(current);
         current=NULL;
         current=prve;
	 }
	}
	int main(void) {
	 struct cell* head;
	 head= build();
	 if (head != NULL) {
	  head = sort(head);
	  print(head);
	 }else
	  printf("NULL");
	 release(head);
	 return 0;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值