单向链表,尾插法

来源:互联网 发布:陌陌群发软件 编辑:程序博客网 时间:2024/06/05 14:11
#include <stdio.h>
#include <stdlib.h>
static int count = 0;
typedef struct node
{
    int data;
    struct node *next;
}Node;
Node * createList()
{
    Node *head = (Node *)malloc(sizeof(Node));
    head->next = NULL;
    Node *pre = head;
    int data;
    scanf("%d",&data);
    while(data)
    {
        count++;
        Node* next = (Node *)malloc(sizeof(Node));
        next->data = data;
        next->next = NULL;
        pre->next = next;
        pre = next;
        scanf("%d",&data);
    }
    return head;
}
void sortList(Node *head,int n)
{
    for(int i =0;i<n-1;i++)
    {
        Node *cur = head->next;
        for(int j = 0;j<n-1-i;j++)
        {
            Node *next = cur->next;
            if(cur->data > next->data)
            {
                int tmp = cur->data;
                cur->data = next->data;
                next->data = tmp;
            }
            cur = cur->next;
        }
    }
}
void traversal(Node *head)
{
    head = head->next;
    while(head)
    {
        printf("%d ",head->data);
        head = head->next;
    }
}
int main(void)
{
    Node *head = createList();//尾插法
    sortList(head,count);//排序
    traversal(head);//遍历
    free(head);
    return 0;
}
                                             
0 0