Given a linked list and a value x, partition it such that all nodes less than x come before nodes greate R than or equal to x.
You should preserve the original relative order of the nodes in each of the.
For example,
Given 1->4->3->2->5->2
and x = 3,
Return 1->2->2->4->3->5
.
The title means that the linked list is divided into two parts based on the X value entered, and the preceding element is less than x (including equal to X) and the order of each node is unchanged.
Idea: Traversing a linked list, when encountering a smaller than x insert to the last node currently less than X, encountering a larger than X, continue to traverse backwards
Define three pointers P Q pur respectively to represent
P: The last node that is currently less than X
Q: Traverse the node backwards
A node after pur:q that is used to insert a node less than x behind the last node that is currently less than X
The code is as follows:
<span style= "FONT-SIZE:18PX;" >/** * 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) {if (head==null| | Head->next==null) return head; ListNode *result=new listnode (0); result->next=head; ListNode *p,*q,*pur;//p is used to point to the last node that is less than X, Q is used to traverse backward when finding a node less than X, put p behind, pur represents an element after Q P=result; Initialize the Q=result; Used to record the first while (Q->next) {if (q->next->val<x) {if (p!=q)//representation The last node currently less than X and the current traversal node Q has other points greater than x {pur=q->next->next; q->next->next=p->next; p->next=q->next; q->next=pur; } else//indicates that all elements currently traversed are less than x q=q->next; p=p->next; } else//if it is greater than X, continue traversing backward q=q->next; } return result->next; }};</span>
Partition List Leetcode