首页 > 其他分享 >力扣-147-对链表进行插入排序

力扣-147-对链表进行插入排序

时间:2022-11-02 14:00:20浏览次数:67  
标签:pre 力扣 head ListNode 147 iteratorNode next 链表 dummyNode

ListNode* insertionSortList(ListNode* head) {
	// 待排节点需要和它前面的节点比较?单链表怎么比,单链表的反向遍历?
	// 只能从头开始找
	// 还要手写链表的交换?
	if (!head->next) return head;
	ListNode* dummyNode = new ListNode(-501);
	dummyNode->next = head;
	ListNode* iteratorNode = head->next;
	ListNode* pre = head;
	while (iteratorNode) {
		for (ListNode* it = dummyNode->next, *prepre = dummyNode; it!=iteratorNode; prepre = it, it = it->next) {
			if (it->val > iteratorNode->val) {
				// 插
				pre->next = iteratorNode->next;
				prepre->next = iteratorNode;
				iteratorNode->next = it;
                break;
			}
		}
		pre = iteratorNode;
		iteratorNode = iteratorNode->next;
	}
	return dummyNode->next;
}

好容易写出来他说我超时

标签:pre,力扣,head,ListNode,147,iteratorNode,next,链表,dummyNode
From: https://www.cnblogs.com/yaocy/p/16850819.html

相关文章