与数组的排序算法相比,由于链表不支持随机访问,故不能使用堆排序和希尔排序,因为他们都依赖于对下标的运算和随机访问某一下标的元素
冒泡排序
C++
int listLength(ListNode* head) {
int l = 0;
while (head) {
l++;
head = head->next;
}
return l;
}
ListNode* bubbleSort(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
int N = listLength(head);
bool sorted = false;
while (!sorted) {
sorted = true;
auto p1 = head, p2 = head->next;
for (int i = 0; i < N && p1 && p2; i++) {
if (p1->val > p2->val) {
swap(p1->val, p2->val);
sorted = false;
}
p1 = p1->next;
p2 = p2->next;
}
N--;
}
return head;
}
Python
def listLength(head):
l = 0
while head:
l += 1
head = head.next
return l
def bubbleSortList(head):
if head is None or head.next is None:
return head
N = listLength(head)
sorted = False
while not sorted:
sorted = True
p1, p2 = head, head.next
for i in range(0, N - 1):
if not (p1 and p2):
break
if p1.val > p2.val:
p1.val, p2.val = p2.val, p1.val
sorted = False
p1, p2 = p1.next, p2.next
N -= 1
return head
Golang
func listLength(head *ListNode) int {
l := 0
for head != nil {
l++
head = head.Next
}
return l
}
func bubbleSortList(head *ListNode) *ListNode{
if head == nil || head.Next == nil {
return head
}
N := listLength(head)
sorted := false
for !sorted {
sorted = true
p1, p2 := head, head.Next
for i := 0; i < N && p1 != nil && p2 != nil; i++ {
if p1.Val > p2.Val {
p1.Val, p2.Val = p2.Val, p1.Val
sorted = false
}
p1, p2 = p1.Next, p2.Next
}
}
return head
}
插入排序
C++
ListNode* cutHead(ListNode*& head) {
if (!head)
return head;
auto res = head;
head = head->next;
res->next = nullptr;
return res;
}
ListNode* insertionSortList(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
auto dummy = new ListNode(0, cutHead(head));
while (head) {
auto p = cutHead(head);
auto n = dummy;
while (n->next && p->val >= n->next->val) {
n = n->next;
}
p->next = n->next;
n->next = p;
}
auto res = dummy->next;
delete dummy;
return res;
}
Python
def cut_head(head)<

最低0.47元/天 解锁文章
7741

被折叠的 条评论
为什么被折叠?



