单链表实现冒泡排序,C++

void BubbleSort(int *a, int len)
{
    LinkNode *head;
    head = CreateLink(a, len);
    LinkNode *n = head->next; //定义n结点
    LinkNode *m = n->next; //定义n的下一个结点, 比较结点
    LinkNode *prev = head; //定义n结点的前驱结点, 方便结点的交换
    LinkNode *rear = NULL; //定义尾结点, 每次把最大的沉到底部之后, 尾结点前移一位
    while(head->next->next != rear)
    {
        while(m->next != rear)
        {
            if(n->data > m->data)
            {
                //如果n>m, 在n结点前插入一个值为m新的结点
                LinkNode *temp = (LinkNode *)malloc(sizeof(LinkNode));
                temp->data = m->data;
                prev->next = temp;
                prev = prev->next;
                temp->next = n;

                if(m->next != NULL)
                {
                    //删除m结点
                    LinkNode *q = m->next;
                    m->next = q->next;
                    m = NULL;
                    free(m);
                    n->next = q;
                }
                else
                    n->next = NULL;
                m = n->next;
            }
            else
            {
                prev = n;
                n = n->next;
                m = n->next;
            }
        }
        rear = m; //尾结点前移
        prev = head; //重新开始一趟排序
        n = head->next;
        m = n->next;
    }

    n = head->next;
    cout << "\n冒泡排序结束的链表为: ";
    while(n->next != NULL)
    {
        cout << n->data << " ";
        n = n->next;
    }

    LinkNode *p;
    while(head != NULL)
    {
        p = head->next;
        head = NULL;
        free(head);
        head = p;
    }
}

LinkNode *CreateLink(int *a, int len)
{
    LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));
    head->next = NULL;
    LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
    head->next = p;
    for (int i = 0; i < len; i++)
    {
        p->data = a[i];
        LinkNode *q = (LinkNode *)malloc(sizeof(LinkNode));
        p->next = q;
        p = q;
    }
    p->next = NULL;
    return head;
}

你可能感兴趣的:(算法)