您好,登錄后才能下訂單哦!
這篇文章主要講解了“C++怎么劃分鏈表”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“C++怎么劃分鏈表”吧!
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
這道題要求我們劃分鏈表,把所有小于給定值的節(jié)點(diǎn)都移到前面,大于該值的節(jié)點(diǎn)順序不變,相當(dāng)于一個(gè)局部排序的問題。那么可以想到的一種解法是首先找到第一個(gè)大于或等于給定值的節(jié)點(diǎn),用題目中給的例子來說就是先找到4,然后再找小于3的值,每找到一個(gè)就將其取出置于4之前即可,代碼如下:
解法一
class Solution { public: ListNode *partition(ListNode *head, int x) { ListNode *dummy = new ListNode(-1); dummy->next = head; ListNode *pre = dummy, *cur = head;; while (pre->next && pre->next->val < x) pre = pre->next; cur = pre; while (cur->next) { if (cur->next->val < x) { ListNode *tmp = cur->next; cur->next = tmp->next; tmp->next = pre->next; pre->next = tmp; pre = pre->next; } else { cur = cur->next; } } return dummy->next; } };
這種解法的鏈表變化順序?yàn)椋?/p>
1 -> 4 -> 3 -> 2 -> 5 -> 2
1 -> 2 -> 4 -> 3 -> 5 -> 2
1 -> 2 -> 2 -> 4 -> 3 -> 5
此題還有一種解法,就是將所有小于給定值的節(jié)點(diǎn)取出組成一個(gè)新的鏈表,此時(shí)原鏈表中剩余的節(jié)點(diǎn)的值都大于或等于給定值,只要將原鏈表直接接在新鏈表后即可,代碼如下:
解法二
class Solution { public: ListNode *partition(ListNode *head, int x) { if (!head) return head; ListNode *dummy = new ListNode(-1); ListNode *newDummy = new ListNode(-1); dummy->next = head; ListNode *cur = dummy, *p = newDummy; while (cur->next) { if (cur->next->val < x) { p->next = cur->next; p = p->next; cur->next = cur->next->next; p->next = NULL; } else { cur = cur->next; } } p->next = dummy->next; return newDummy->next; } };
此種解法鏈表變化順序?yàn)椋?/p>
Original: 1 -> 4 -> 3 -> 2 -> 5 -> 2
New:
Original: 4 -> 3 -> 2 -> 5 -> 2
New: 1
Original: 4 -> 3 -> 5 -> 2
New: 1 -> 2
Original: 4 -> 3 -> 5
New: 1 -> 2 -> 2
Original:
New: 1 -> 2 -> 2 -> 4 -> 3 -> 5
感謝各位的閱讀,以上就是“C++怎么劃分鏈表”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對C++怎么劃分鏈表這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。