C++實現(xiàn)LeetCode(86.劃分鏈表)
[LeetCode] 86.Partition List 劃分鏈表
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é)點都移到前面,大于該值的節(jié)點順序不變,相當(dāng)于一個局部排序的問題。那么可以想到的一種解法是首先找到第一個大于或等于給定值的節(jié)點,用題目中給的例子來說就是先找到4,然后再找小于3的值,每找到一個就將其取出置于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;
}
};
這種解法的鏈表變化順序為:
1 -> 4 -> 3 -> 2 -> 5 -> 2
1 -> 2 -> 4 -> 3 -> 5 -> 2
1 -> 2 -> 2 -> 4 -> 3 -> 5
此題還有一種解法,就是將所有小于給定值的節(jié)點取出組成一個新的鏈表,此時原鏈表中剩余的節(jié)點的值都大于或等于給定值,只要將原鏈表直接接在新鏈表后即可,代碼如下:
解法二
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;
}
};
此種解法鏈表變化順序為:
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
到此這篇關(guān)于C++實現(xiàn)LeetCode(86.劃分鏈表)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)劃分鏈表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言詳細(xì)分析浮點數(shù)在內(nèi)存中的儲存
我們在日常生活中和編程中都會用到小數(shù),比如:3.1415926、29.9、1E10(科學(xué)計數(shù)法也是浮點型)。在C語言中的浮點型類型有:float,double,long double。那么浮點數(shù)在這些浮點型的內(nèi)存之中又是如何儲存的呢,這就是今天我們要分享的2022-06-06
淺談帶緩沖I/O 和不帶緩沖I/O的區(qū)別與聯(lián)系
下面小編就為大家?guī)硪黄獪\談帶緩沖I/O 和不帶緩沖I/O的區(qū)別與聯(lián)系。小編覺得挺不錯的現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
C++實現(xiàn)產(chǎn)生隨機(jī)數(shù)和相應(yīng)的猜拳小游戲?qū)嵗a
C++中沒有自帶的random函數(shù),要實現(xiàn)隨機(jī)數(shù)的生成就需要使用rand()和srand()。下面這篇文章主要給大家介紹了關(guān)于C++實現(xiàn)產(chǎn)生隨機(jī)數(shù)和相應(yīng)的猜拳小游戲的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-09-09
C++標(biāo)準(zhǔn)庫中sstream與strstream的區(qū)別詳細(xì)解析
以下是對C++標(biāo)準(zhǔn)庫中sstream與strstream的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下2013-09-09

