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

来源:互联网 发布:linux输入中文 编辑:程序博客网 时间:2024/06/03 22:53

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

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。

Input

第一行输入整数个数N;
第二行输入N个无序的整数。

Output

依次输出有序链表的结点值。

Example Input

633 6 22 9 44 5

Example Output

5 6 9 22 33 44
在建表的过程中,将一个新的数据放入新表之前遍历找到第一个大于该数据的元素,将新数据插入即可。
#include<stdio.h>#include<stdlib.h>typedef struct node{    int data;    struct node *next;}*linkList;int count = 0;/*void creatList(linkList &L,int n){    struct node *p, *tail;    L =new node;    tail = L;    for(int i = 0; i < n; i++){        p = (struct node*)malloc(sizeof(struct node));        scanf("%d", &p->data);        p->next = NULL;        tail->next = p;        tail = p;    }};*/void outputData(linkList &L){struct node *p;p = L->next;    while(p){    if(p->next == NULL)    printf("%d\n", p->data);    else         printf("%d ", p->data);        p = p->next;    }}void sort_creat(linkList &L, int n){linkList p, tail, q;L = new node;L->next = NULL;for(int i = 0; i < n; i++){p = new node;scanf("%d", &p->data);if(i == 0){p->next = L->next;L->next = p;}else {q = L;tail = L->next;while(tail){if(p->data < tail->data){q->next = p;p->next = tail;break;}else {q = tail;tail = tail->next;}}if(!tail){p->next = NULL;q->next = p;}}}}int main(){    int n;    scanf("%d", &n);    linkList L;    sort_creat(L, n);    outputData(L);    return 0;}


阅读全文
1 0
原创粉丝点击