山东理工OJ【2121】数据结构实验之链表六:有序链表的建立(插排法)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                山东理工OJ【2121】数据结构实验之链表六:有序链表的建立(插排法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                
                            
                            
                              
第二行輸入N個無序的整數。
#include <stdio.h> #include <stdlib.h> struct node {int data;struct node *next; }*head; int main() {head=(struct node*)malloc(sizeof(struct node));head->next=NULL;int n,i;struct node *p,*q,*r;scanf("%d",&n);p=(struct node*)malloc(sizeof(struct node));q=(struct node*)malloc(sizeof(struct node));//為當前結點和前驅結點開辟空間for(i=0; i<n; i++){r=(struct node*)malloc(sizeof(struct node));scanf("%d",&r->data);p=head->next;q=head;while(p!=NULL){if(r->data<p->data){q->next=r;r->next=p;break;}//若結點r的數據比結點p的數據小,則把r插入到q和p之間;q=p;p=p->next;}if(p==NULL){q->next=r;r->next=NULL;}//若結點p為NULL,意味著此時r中的數據大于之前的所有數據,就把r插在最后}p=head->next;while(p!=NULL){if(p->next==NULL)printf("%d\n",p->data);elseprintf("%d ",p->data);p=p->next;}return 0; }
 
 
 
 
                        
                        
                        數據結構實驗之鏈表六:有序鏈表的建立
Time Limit: 1000ms?? Memory limit: 65536K??有疑問?點這里^_^
題目描述
輸入N個無序的整數,建立一個有序鏈表,鏈表中的結點按照數值非降序排列,輸出該有序鏈表。輸入
第一行輸入整數個數N;第二行輸入N個無序的整數。
輸出
依次輸出有序鏈表的結點值。示例輸入
6 33 6 22 9 44 5示例輸出
5 6 9 22 33 44提示
不得使用數組!#include <stdio.h> #include <stdlib.h> struct node {int data;struct node *next; }*head; int main() {head=(struct node*)malloc(sizeof(struct node));head->next=NULL;int n,i;struct node *p,*q,*r;scanf("%d",&n);p=(struct node*)malloc(sizeof(struct node));q=(struct node*)malloc(sizeof(struct node));//為當前結點和前驅結點開辟空間for(i=0; i<n; i++){r=(struct node*)malloc(sizeof(struct node));scanf("%d",&r->data);p=head->next;q=head;while(p!=NULL){if(r->data<p->data){q->next=r;r->next=p;break;}//若結點r的數據比結點p的數據小,則把r插入到q和p之間;q=p;p=p->next;}if(p==NULL){q->next=r;r->next=NULL;}//若結點p為NULL,意味著此時r中的數據大于之前的所有數據,就把r插在最后}p=head->next;while(p!=NULL){if(p->next==NULL)printf("%d\n",p->data);elseprintf("%d ",p->data);p=p->next;}return 0; }
轉載于:https://www.cnblogs.com/jiangyongy/p/3971703.html
總結
以上是生活随笔為你收集整理的山东理工OJ【2121】数据结构实验之链表六:有序链表的建立(插排法)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: (Eclipse打包问题)Export
- 下一篇: 在企业内部使用openssl创建私有CA
