1. 程式人生 > >【LeetCode】86. Partition List(C++)

【LeetCode】86. Partition List(C++)

地址:https://leetcode.com/problems/partition-list/

題目:

Given a linked list and a value x x , partition it such that all nodes less than x x

come before nodes greater than or equal to x x .

You should preserve the original relative order of the nodes in each of the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output

: 1->2->2->4->3->5

理解:

給了一個連結串列,一個x,要求把這個連結串列分為兩部分,前面是小於x的,後面是大於等於x的,且不能改變原來的相對順序。

實現:

lessPre:小於部分的尾指標
morePre:大於等於部分的尾指標
lessHead:小於部分的頭指標
moreHead:大於等於部分的頭指標

class Solution {
public:
	ListNode* partition(ListNode* head, int x) {
		ListNode* lessPre = nullptr;
		ListNode*
morePre = nullptr; ListNode* lessHead = nullptr; ListNode* moreHead = nullptr; ListNode* p = head; while (p) { if (p->val < x) { if (!lessHead) { lessHead = p; lessPre = p; } else { lessPre->next = p; lessPre=lessPre->next; } } else { if (!moreHead) { moreHead = p; morePre = p; } else { morePre->next = p; morePre = morePre->next; } } p = p->next; } if (lessHead) { lessPre->next = moreHead; if(moreHead) morePre->next = nullptr; return lessHead; } else if (moreHead) { morePre->next = nullptr; return moreHead; } else return nullptr; } };

可以考慮用帶頭結點的連結串列,能夠簡化很多操作。

class Solution {
public:
	ListNode* partition(ListNode* head, int x) {
		ListNode* lessHead = new ListNode(0);
		ListNode* moreHead = new ListNode(0);
		ListNode* lessPre = lessHead;
		ListNode* morePre = moreHead;
		ListNode* p = head;
		while (p) {
			if (p->val < x) {
					lessPre->next = p;
					lessPre=lessPre->next;
			}
			else {
				morePre->next = p;
				morePre = morePre->next;	
			}
			p = p->next;
		}
		lessPre->next = moreHead->next;
		morePre->next = nullptr;
		return lessHead->next;
	}
};