题目要求:
现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
过程:
解这道题目,最重要的是建立两个链表,将小于x的结构体放到一个链表lesshead,大于x的结构体放到另一个链表greaterhead。最后将两个链表进行合并。
最后切记,一定要将greatertail->next置为空,保证不会出现以下情况:
代码实现:
/*
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
if(pHead == NULL)
{
return NULL;
}
//1、建立两个链表
ListNode* lesshead, *lesstail;
ListNode* greaterhead, *greatertail;
lesshead = lesstail = (ListNode*)malloc(sizeof(ListNode));
greaterhead = greatertail = (ListNode*)malloc(sizeof(ListNode));
lesshead->next = greaterhead->next = NULL;
//2、对原链表每个结构体对应的val值与x值进行比较,小于x的放到lesshead为头指针的链表中,大于x的放到greaterhead为头指针的链表之中。每回遍历,lesstail和greatertail都指向其下一个。
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;
}
//3、合并两个链表
lesstail->next = greaterhead->next;
greatertail->next = NULL;
ListNode* List = lesshead->next;
free(lesshead);
free(greaterhead);
return List;
}
};