86. Partition List
Posted hozhangel
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
Example:
Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode* new_node = new ListNode(0); new_node->next = head; ListNode* pre = new_node; ListNode* curr = head; ListNode* move = head; while (curr != NULL && curr->val < x) //for the preserve of the original relative order of the nodes { move = curr; pre = curr; curr = curr->next; } while (curr != NULL) { if (curr->val >= x) //if the value bigger than x, curr just index the next node { move = curr; curr = curr->next; } else if(curr->val < x) //if the value smaller than x , move it to the head //(preserve of the original relative order of the nodes when move the node ahead) { //pre is the last node of which is smaller than x, //move‘s duty is traverse //cur is the current node move->next = curr->next; curr->next = pre->next; pre->next = curr; pre = curr; curr = move->next; } } ListNode* temp = new_node; delete new_node; return temp->next; } };
referenceL:C++ one pass solution
以上是关于86. Partition List的主要内容,如果未能解决你的问题,请参考以下文章