怎么对c++单链表冒泡算法反转?

关注
怎么对c++单链表冒泡算法反转?www.shan-machinery.com

//冒泡排序,这里我用的是交换链表值的方式实现的,结果是从小到大排序

//测试链接:sort-list_牛客网

/**

* Definition for singly-linked list.

* struct ListNode {

* int val;

* ListNode *next;

* ListNode(int x) : val(x), next(NULL) {}

* };

*/

//链表冒泡排序

class Solution {

public:

ListNode *sortList(ListNode *head) {

if(head == nullptr || head->next == nullptr) return head;

ListNode* p1 = head;

ListNode* p2 = nullptr;

while(p2 != head){

while(p1 != nullptr&& p1->next != nullptr&& p1->next != p2){

ListNode* pNext = p1->next;

if(p1->val > pNext->val){

int temp = p1->val;

p1->val = pNext->val;

pNext->val = temp;

}

p1 = p1->next;

}

p2 = p1;

p1 = head;

}

return head;

}

};

https://www.shan-machinery.com