Partition List Solutions in C++
Number 86
Difficulty Medium
Acceptance 41.7%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/partition-list/// Author : Hao Chen// Date : 2014-06-21#include <stdio.h>struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *partition(ListNode *head, int x) {ListNode fakeHead(0);fakeHead.next = head;head = &fakeHead;ListNode *pos = NULL;for(ListNode *p = head; p!=NULL && p->next!=NULL; ){if (!pos && p->next->val >= x){pos = p;p=p->next;continue;}if (pos && p->next->val < x){ListNode *pNext = p->next;p->next = pNext->next;pNext->next = pos->next;pos->next = pNext;pos = pNext;continue;}p=p->next;}return head->next;}void printList(ListNode* h){while(h!=NULL){printf("%d ", h->val);h = h->next;}printf("\n");}ListNode* createList(int a[], int n){ListNode *head=NULL, *p=NULL;for(int i=0; i<n; i++){if (head == NULL){head = p = new ListNode(a[i]);}else{p->next = new ListNode(a[i]);p = p->next;}}return head;}int main(){//int a[] = {1}; int x =2;//int a[] = {2,3,1}; int x=2;int a[] = {3,1,2}; int x=3;ListNode* p = createList(a, sizeof(a)/sizeof(int));printList(p);p = partition(p, x);printList(p);return 0;}
C++ solution by pezy/LeetCode
#include <cstddef>struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution {public:ListNode *partition(ListNode *head, int x) {ListNode pre_head(0), *pre = &pre_head;for (; head && head->val < x; head = head->next)pre = pre->next = head;for (ListNode *p=head, **pp=&head; p; p = *pp)if (p->val < x) {pre = pre->next = p;*pp = p->next;}else pp = &(*pp)->next;pre->next = head;return pre_head.next;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/partition-list/description//// Author : liuyubobobo/// Time : 2018-07-07#include <iostream>using namespace std;/// Definition for singly-linked list.struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};/// Linear Scan/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:ListNode* partition(ListNode* head, int x) {ListNode* dummyHead1 = new ListNode(-1);ListNode* dummyHead2 = new ListNode(-1);ListNode* prev1 = dummyHead1;ListNode* prev2 = dummyHead2;for(ListNode* cur = head ; cur != NULL ;){if(cur->val < x){prev1->next = cur;cur = cur->next;prev1 = prev1->next;prev1->next = NULL;}else{prev2->next = cur;cur = cur->next;prev2 = prev2->next;prev2->next = NULL;}}prev1->next = dummyHead2->next;ListNode* ret = dummyHead1->next;delete dummyHead1;delete dummyHead2;return ret;}};int main() {return 0;}