#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define LISTSIZE 1000 #define LISTMAX 100 typedef int Elemtype; typedef struct LNode //定义单链表结点类型 { Elemtype data; //数据域 struct LNode *next; //指针域 }LNode,*LinkList; LinkList CreatList1(LinkList &L) {//从表头到表尾逆向建链表,每次均在头结点之后插入元素int x,t; //设元素类型为整形L = (LinkList)malloc(sizeof(LNode)); //建立头结点L->next = NULL;//初始化空链表LNode *s,*r=L; //r未表尾指针scanf("%d",&t); //输入结点值while(t--) //输入9999表示循环结束{scanf("%d",&x);s = (LNode *)malloc(sizeof(LNode));s->data = x;s->next=L->next;L->next = s;//将新结点插入表中,L为头指针}//while循环结束return L; } LinkList sorting(LinkList &head) {LNode *p,*q;int t; for( p = head->next;p!=NULL;p=p->next) {for(q=p->next;q!=NULL;q=q->next){if(p->data>q->data){t = p->data;p->data = q->data;q->data = t;}} }return head; } void display(struct LNode *head) { LNode *p; p = head->next; while(p!=NULL) { if(p->next==NULL) { printf("%d\n",p->data); } else { printf("%d ",p->data); } p=p->next; } } int main() { LNode *L; L = CreatList1(L);sorting(L); display(L); return 0; }
解法二
#include <stdio.h> #include <malloc.h> int main() { int n,i; scanf("%d",&n); struct node { int data; struct node *next; }; struct node * head,* tail,* p; head=(struct node *)malloc(sizeof(struct node)); head->next=NULL; for (i=0; i<n; i++) { p=(struct node *)malloc(sizeof(struct node)); scanf("%d",&p->data); tail=head; while(tail->next!=NULL) { if (tail->next->data>p->data) break; tail=tail->next; } p->next=tail->next; tail->next=p; } p=head->next; while(p!=NULL) { if(p->next==NULL) printf("%d\n",p->data); else printf("%d ",p->data); p=p->next; } return 0; }
转载于:https://www.cnblogs.com/CCCrunner/p/6444606.html
相关资源:JAVA上百实例源码以及开源项目