分割链表
/**
* 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 Lhead(0);
ListNode Mhead(0);
ListNode* pNode=head;
ListNode* lesshead=&Lhead;
ListNode* morehead=&Mhead;
ListNode* newhead=&Lhead;
while(pNode)
{
if(pNode->val>=x)
{
morehead->next=pNode;
morehead=morehead->next;
}
else
{
lesshead->next=pNode;
lesshead=lesshead->next;
}
pNode=pNode->next;
}
//进行链表的连接
lesshead->next=(&Mhead)->next;
morehead->next=NULL;
return newhead->next;
}
};