数据结构实验之链表六:有序链表的建立

数据结构实验之链表六:有序链表的建立

Description
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
Input
第一行输入整数个数N;
第二行输入N个无序的整数。
Output
依次输出有序链表的结点值。
Samples
Sample #1
Input
6
33 6 22 9 44 5
Output
5 6 9 22 33 44

分析:

插入时主要需要找前驱,写的有点麻烦,步骤应该能继续简化

#include <bits/stdc++.h>
using namespace std;
typedef struct node{
	int data;
	struct node *next;
}s;
int n,m,x,k=0;
int main(){
    cin>>n;
    int a;
    s *head,*p,*q,*r,*t;
    head=(struct node *)malloc (sizeof(struct node));
    p=(struct node *)malloc (sizeof(struct node));
    s *tail=head;
    cin>>a;
    p->data=a;
    head->next=p;
    p->next=NULL;
    for(int i=1;i<n;i++){
    	cin>>a;
    	r=head;
    	q=head->next;
    	while(a>q->data&&q->next!=NULL){
    		q=q->next;
    		r=r->next;
		} 
		t=(struct node *)malloc (sizeof(struct node));
		t->data=a;
		if(q->next==NULL){
			if(q->data<a){
				q->next=t;
				t->next=NULL;
			}
			else{
				t->next=q;
			r->next=t;
			}
		}
		else{	
			t->next=q;
			r->next=t;
		}
    }
    p=head->next;
    while(p!=NULL){
    	cout<<p->data<<" ";
    	p=p->next;
	}  
	cout<<endl; 
    return 0;
}


  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值