目录
题目来源:
题目描述:
代码实现:
1、不带有哨兵位的头结点。
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
ListNode* head1,*tail1,*head2,*tail2;
head1 = tail1 = head2 = tail2 = NULL;
while(pHead)
{
if(pHead->val < x)
{
if(tail1 == NULL)
{
head1=tail1=pHead;
}
else
{
tail1->next = pHead;
tail1 = pHead;
}
pHead=pHead->next;
}
else
{
if(tail2 == NULL)
{
head2=tail2=pHead;
}
else
{
tail2->next = pHead;
tail2 = pHead;
}
pHead=pHead->next;
}
}
if(head1 == NULL && head2 == NULL)
{
return NULL;
}
if(head1==NULL && head2 != NULL)
{
return head2;
}
if(head1!=NULL && head2 == NULL )
{
tail1->next =NULL;
return head1;
}
tail2->next =NULL;
tail1->next = head2;
return head1;
}
};
2、带有哨兵位的头结点。
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
ListNode* lessHead,*lessTail,*greaterHead,*greaterTail;
lessHead = lessTail = (ListNode*)malloc(sizeof(ListNode));
greaterHead = greaterTail = (ListNode*)malloc(sizeof(ListNode));
ListNode* cur = pHead;
while(cur)
{
if(cur->val < x)
{
lessTail->next = cur;
lessTail = lessTail->next;
}
else
{
greaterTail->next = cur;
greaterTail = greaterTail->next;
}
cur = cur->next;
}
lessTail->next = greaterHead->next;
greaterTail->next = NULL;
ListNode* list = lessHead->next;
free(lessHead);
free(greaterHead);
return list;
}
};
分析过程:
1、不带有哨兵位的头结点。
过程:
1、我们创建两个新链表分别存放小于x的所有值和大于x的所有值。比x小的链表的头结点和尾结点分别为head1,list1;比x大的链表的头结点和尾结点分别为head2,list2。
2、起始我们将head1,list1,head2,list2置空,第一个元素判断完后,我们就将对应的head和tail赋值为phead,随着phead遍历原链表,我们将原链表分为两个不同的链表。
3、最后我们将tail1->next指向head2即可。
注意特殊情况:
1、将原链表分完后head1或者head2有链表为空,因此我们需要做出判断。
if(head1 == NULL && head2 == NULL)
{
return NULL;
}
if(head1==NULL && head2 != NULL)
{
return head2;
}
if(head1!=NULL && head2 == NULL )
{
tail1->next =NULL;
return head1;
}
2、有可能造成链表环化。
为了避免这个问题,我们一定要将tail2->next 置空,这样就会比较造成环化。
2、带有哨兵位的头结点。
主要思路和不带有哨兵位的头结点一样,只是在结构和细节的处理上有些差别。
差别:
1、返回头结点需要返回lessHead->next,但是如果不释放两个头结点会有资源浪费,因此再创建一个list来保存lessHead->next,就可以free两个节点。
2、lessTail->next连接的是greaterHead->next,而不是greaterHead。
同时,为了避免成环,greaterTail->next一定要置空
(本题完)