计算机机考内容问题。。

数据以链表方式存储,编写链表插入排序算法(需预先创建符合要求的单链表)。

你好,问题解决了没,计算机机考应该用的C语言吧,我写了一个C语言的代码。你看看对你有没有帮助。
**展示效果: **

图片说明

**代码如下: **

/**
 * C语言实现
 */
#include <stdio.h>
#include <stdlib.h>
// #include<malloc.h> // 苹果系统下不用导入这个库函数,如果是windows,取消掉注释

// 定义结构体
struct ListNode {
    int val;
    struct ListNode *next;
};

// 单链表排序算法
struct ListNode* SortList(struct ListNode* head){
    struct ListNode *tmp, *cur, *pre, *next;

    if (!head)
        return NULL;

    cur = head->next;
    head->next = NULL;
    while(cur) {
        pre = head;
        next = cur->next;
        for (tmp=head; ; tmp=tmp->next) {
            if (!tmp) {
                cur->next = NULL;
                pre->next = cur;
                break;
            }
            if (tmp->val > cur->val) {
                if (tmp == head) {
                    cur->next = head;
                    head = cur;
                } else {
                    cur->next = pre->next;
                    pre->next = cur;
                }
                break;
            }
            pre=tmp;
        }
        cur = next;
    }
    return head;
}

// 创建链表
struct ListNode* createList(){
    struct ListNode *head,*p,*q;

    int len;
    head =(struct ListNode *)malloc(sizeof(struct ListNode)); // 创建新的空间
    printf("需要排序的元素个数:\n");
    scanf("%d",&len);
    printf("请输入元素\n");
    scanf("%d",&head->val);
    p = head;
    for (int i = 1; i < len; ++i)
    {
        q =(struct ListNode *)malloc(sizeof(struct ListNode));
        scanf("%d",&q->val);

        p->next = q;
        // 当前指针指向下一个元素
        p = q;
    }
    p->next = NULL;
    return head ;

}

// 打印链表
void printList(struct ListNode *head)
{
    struct ListNode* p;
    p=head;
    if(p==NULL)
    {
        printf("链表中没有元素\n");
    } else {
        while(1)
        {
            printf("%d\t",p->val);
            if(p->next != NULL)
            {
                p=p->next;
            } else {
                break;
            }
        }
    }
}

// 主函数
int main()
{
    struct ListNode* head , *sortHead;
    // 创建链表
    head = createList();
    printf("\n-----排序前-----\n\n");
    printList(head);
    // 对链表进行排序
    printf("\n-----排序后-----\n\n");
    sortHead = SortList(head);
    printList(sortHead);
    return 0 ;
}