编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
解题思路:
构造两个新的带头单向链表;将小于X的插到lessHead链表上,将大于等于X的插到greatHead链表上。最后合并两个链表,去掉带头结点。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
ListNode* lessHead = (ListNode*)malloc(sizeof(ListNode));
lessHead->next = NULL;
ListNode* lessTail = lessHead;
ListNode* greatHead = (ListNode*)malloc(sizeof(ListNode));
greatHead->next = NULL;
ListNode* greatTail = greatHead;
ListNode* cur = pHead;
while (cur)
{
if (cur->val<x)
{
lessTail->next = cur;
lessTail = cur;
}
else
{
greatTail->next = cur;
greatTail = cur;
}
cur = cur->next;
}
greatTail->next = NULL;
lessTail->next = greatHead->next;
ListNode* list = lessHead->next;
free(lessHead);
free(greatHead);
return list;
}
};