单链表的建立、排序、打印

来源:互联网 发布:五大贵重宝石知乎 编辑:程序博客网 时间:2024/06/02 02:53
#include<cstdio>
#include<cstdlib>
#include <cstring>
using namespace std;
struct node
{
    int num;
    char name[10];
    struct node *next;
};
struct node *createlink(int n)
{
    int i;
    struct node *head,*p,*q;
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    q=head;
    for(i=0;i<n;i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        scanf("%d",&p->num);
        scanf("%s",p->name);
        q->next=p;
        q=p;
        p->next=NULL;
    }
    return head;
}
void sort(struct node *head)
{
    struct node *p,*q,t,*m;
    p=head->next;
    if(p!=NULL)
    {
        while(p->next!=NULL)
        {
            q=p->next;
            while(q!=NULL)
            {
                if(q->num>p->num)
                {
                    t=*p;
                    *p=*q;
                    *q=t;
                    m=p->next;
                    p->next=q->next;
                    q->next=m;
                }
                q=q->next;
            }
            p=p->next;
        }
    }
}

void disp(struct node *head)
{
    struct node *p;
    p=head->next;
    while(p!=NULL)
    {
        printf("%d\n",p->num);
        printf("%s\n",p->name);
        p=p->next;
    }
    printf("\n\n");
}
int main()
{
    struct node *head;
    head=createlink(3);
    disp(head);
    sort(head);
    disp(head);
    return 0;
}

0 0
原创粉丝点击