逆置、排序(冒泡排序)单链表

逆置单链表:首先定义一个新的指针newHead指向当前链表的第一个节点,然后定义cur1记录链表的下一个节点,使该节点指向newHead,依次类推,完成单链表的逆置
这里写图片描述

typedef struct SListNode
{
    struct SListNode* _next;
    DataType _data;
}SListNode;
SListNode* SListReverse(SListNode* list)
{
    SListNode* newHead = list;
    SListNode* cur1;
    SListNode* cur2;
    assert(list);
    cur1 = list->_next;
    newHead->_next = NULL;
    while (cur1)
    {
        cur2 = cur1;
        cur1 = cur1->_next;
        cur2->_next = newHead;
        newHead = cur2;
    }
    list = newHead;
    return list;
}

冒泡排序:

void SListBubbleSort(SListNode* list)
{
    assert(list);
    SListNode* cur = list;
    SListNode* next = list->_next;
    int i = 0;
    int count = 1;
    int j = 0;
    while (cur->_next)
    {
        cur = cur->_next;
        count++;
    }
    cur = list;
    for (i = 0; i < count - 1; i++)
    {
        cur = list;
        next = list->_next;
        for (j = 0; j < count - 1 - i; j++)
        {

            if (cur->_data>next->_data)
            {
                int tmp = next->_data;
                next->_data = cur->_data;
                cur->_data = tmp;
            }
            cur = cur->_next;
            next = next->_next;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/smx_dd/article/details/79983045