文章

19

粉丝

225

获赞

19

访问

42.5k

头像
c-头插法
P1015 贵州大学机试题
发布于2023年3月26日 09:07
阅读数 2.3k

 先对数组进行冒泡排序,然后头插法创建链表,最后就链表遍历输出即可,也可以用尾插法啦。

#include<stdio.h>
#include<stdlib.h>
struct node{
	struct node*next;
	int data;
};
struct node* create(int a[],int len){
	int i;
	struct node*head=(struct node*)malloc(sizeof(struct node));
	struct node*t=(struct node*)malloc(sizeof(struct node));
	t=NULL;
	for(i=0;i<len;i++){
		struct node*p=(struct node*)malloc(sizeof(struct node));
		p->data=a[i];
		p->next=t;
		t=p;
		head->next=t;
	}
	return head;
}
int main(){
	int a[5];
	int i,j,t;
	struct node*head;
	for(i=0;i<5;i++)
		scanf("%d",&a[i]);
	for(i=0;i<5;i++){
		for(j=0;j<5-i-1;j++){
			if(a[j]<a[j+1]){
				t=a[j];
				a[j]=a[j+1];
				a[j+1]=t;
			}
		}
	}

	head=create(a,5);
	head=head->next;
	while(head!=NULL){
		printf("%d ",head->data);
		head=head->next;
	}
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发