Cover image for Interview Classic 150 Problem P86: Partition List

Interview Classic 150 Problem P86: Partition List


Timeline

Timeline

2025-11-21

init

linked list

Problem:

The meaning is to put those greater than k in front and those less than k in the back, but the relative order among the group greater than k remains unchanged, and the relative order among the group less than k also remains unchanged.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
struct ListNode {	int val;	ListNode *next;	ListNode()		: val(0)		, next(nullptr)	{	}	ListNode(int x)		: val(x)		, next(nullptr)	{	}	ListNode(int x, ListNode *next)		: val(x)		, next(next)	{	}};class Solution {    public:	ListNode *partition(ListNode *head, int x)	{		ListNode *virt_node = new ListNode;		virt_node->next = head;		ListNode *prev = virt_node, *p, *tmp;		while (prev->next != nullptr && prev->next->val < x) {			prev = prev->next; //Find the predecessor node of the first node greater than or equal to x.		}		if (prev->next == nullptr) { //all vals < x			return head;		}		p = prev;		while (p->next != nullptr) {			if (p->next->val < x) {				tmp = p->next;				p->next = tmp->next;				tmp->next = prev->next;				prev->next = tmp;				prev = tmp;			} else {				p = p->next;			}		}		head = virt_node->next;		delete virt_node;		return head;	}};
Loading comments…