您好,登錄后才能下訂單哦!
這篇文章主要講解了“C++怎么劃分鏈表”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“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.
這道題要求我們劃分鏈表,把所有小于給定值的節點都移到前面,大于該值的節點順序不變,相當于一個局部排序的問題。那么可以想到的一種解法是首先找到第一個大于或等于給定值的節點,用題目中給的例子來說就是先找到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
此題還有一種解法,就是將所有小于給定值的節點取出組成一個新的鏈表,此時原鏈表中剩余的節點的值都大于或等于給定值,只要將原鏈表直接接在新鏈表后即可,代碼如下:
解法二
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
感謝各位的閱讀,以上就是“C++怎么劃分鏈表”的內容了,經過本文的學習后,相信大家對C++怎么劃分鏈表這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。