给定链表的头结点 head 请将其按 升序 排列并返回 排序后的链表不用递归不用迭代java用冒泡或者选择进行排序
以下是使用冒泡排序进行链表排序的示例代码:
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
int length = 0;
// 计算链表长度
while (cur.next != null) {
cur = cur.next;
length++;
}
for (int i = 0; i < length - 1; i++) {
cur = dummy.next;
ListNode prev = dummy;
for (int j = 0; j < length - i - 1; j++) {
if (cur.val > cur.next.val) {
ListNode next = cur.next;
cur.next = next.next;
next.next = cur;
prev.next = next;
}
prev = cur;
cur = cur.next;
}
}
return dummy.next;
}
以下是使用选择排序进行链表排序的示例代码:
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
ListNode minPre = findMinNodePre(cur);
if (minPre == null) {
break;
}
ListNode min = minPre.next;
minPre.next = min.next;
min.next = cur.next;
cur.next = min;
cur = cur.next;
}
return dummy.next;
}
private ListNode findMinNodePre(ListNode head) {
ListNode minPre = head;
ListNode min = head.next;
ListNode cur = head.next;
ListNode prev = head;
while (cur != null) {
if (cur.val < min.val) {
minPre = prev;
min = cur;
}
prev = cur;
cur = cur.next;
}
return minPre;
}
以上两个示例代码中,ListNode 是链表节点的定义,包含一个整数值 val 和一个指向下一个节点的指针 next。head 是链表的头结点。函数 sortList 对链表进行排序,返回排序后的链表头结点
原文地址: https://www.cveoy.top/t/topic/iqfB 著作权归作者所有。请勿转载和采集!