【算法题】链表冒泡排序

实现单链表的冒泡排序

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;

struct ListNode
{
    ListNode* next;
    int value;
};

bool List_insert(ListNode ** phead, int x, int i)
{
//空指针
    if (phead == NULL)
    {
        return 0;
    }
    ListNode * pCurrent(NULL);

//头插入
    if (i==1)
    {
        pCurrent = *phead;
        ListNode * pNew = new ListNode;
        pNew->value = x;
        pNew->next = pCurrent;
        *phead = pNew;
        return 1;
    }
//非头插入
    pCurrent = *phead;
    ListNode * pfront(NULL);
    int k(1);
    while (k < i && pCurrent != NULL)
    {
        pfront = pCurrent;
        pCurrent = pCurrent->next;
        k++;
    }
    if (k != i)
    {
        return 0;
    }
    ListNode * pNew = new ListNode;
    pNew->value = x;
    pNew->next = pCurrent;
    pfront->next = pNew;
    return 1;
}

void List_print(ListNode * phead)
{
    while (phead!=NULL)
    {
        cout << phead->value;
        phead = phead->next;
    }
}

void List_Bubble_sort(ListNode** phead)
{
    if (phead==NULL||*phead==NULL|| (*phead)->next==NULL   )
    {
        return;
    }
    auto iter = *phead;
    ListNode * stop = NULL;

    for (; stop != *phead;)
    {
        for (; iter->next != stop; iter = iter->next)
        {
            if (iter->value > iter->next->value)
            {
                std::swap(iter->value, iter->next->value);
            }
        }
        stop = iter;
        iter = *phead;
    }
}

int main()
{
    ListNode * phead = NULL;
    List_insert(&phead, 1, 1);
    List_insert(&phead, 2, 1);
    List_insert(&phead, 3, 1);
    List_insert(&phead, 0, 2);
    List_Bubble_sort(&phead);//冒泡排序
    List_print(phead);

    return 0;
}

更简单的实现:

void List_Bubble_sort(ListNode** phead)
{
    ListNode * _tmp = *phead;
    ListNode * _node= *phead;
    int temp;
    for (; _tmp->next;_tmp=_tmp->next)
    {
        for (_node = *phead; _node->next;_node= _node->next)
        {
            if (_node->value>_node->next->value)
            {
                std::swap(_node->value, _node->next->value);
            }
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值