😾 博客主页: 爱吃bug的猿
🚀博客专栏: 数据结构,C语言初阶进阶全流程讲解
✨ 每日激励:欲达高峰,必忍其痛;欲戴王冠,必承其重✨
😽😽😽如果喜欢博主的文章,可以给博主点波赞和关注加速博主更新
1.前言
- 我将会分别实现有带哨兵位和无哨兵位的代码,通过对比我们可以发现哪种更加便捷
- 代码实现的方式千千万,选对思路才能达到事半功倍的效果
- 链表分割,要注意题中说的是不能改变原来的数据顺序,也就是说相对顺序不能变,比如,2 3 7 5,选5作为分割点,分完为2 3 5 7 ,2还是在3的前面,可以用尾插来实现这里的思路
2.带哨兵位代码实现及思路
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
struct ListNode * lessnode,*lesstail,*greatnode,*greattail;
lessnode = lesstail = (struct ListNode *)malloc(sizeof(struct ListNode ));
greatnode = greattail = (struct ListNode *)malloc(sizeof(struct ListNode ));
struct ListNode * cur = pHead;
while(cur)
{
if(cur->val < x)
{
lesstail->next = cur;
lesstail = lesstail->next;
}
else
{
greattail->next = cur;
greattail = greattail->next;
}
cur = cur->next;
}
lesstail->next = greatnode->next;
greattail->next = NULL;
pHead = lessnode->next;
free(lessnode);
free(greatnode);
return pHead;
}
};
- 1.malloc开辟两块结构体大小的空间,相当于两个链表,lessnode,greatnode
- 2.小于x的尾插到lessnode里,大于的尾插到greatnode里
- 3.最后,lesstail来到4处,让lesstail指向5,那么就将整个链表串了起来
- 4.一定要注意,遍历完cur之后,greattail来到7的位置,而通过原链表可以看到,7指向下一个位置4,所以我们需要在循环完后将greattail置为空,切忌在循环里就将其置为空,因为greattail存的地址是原链表中的某一个,改变greattail会改变cur,而我们只需将7所在结点的next置为空就达到目的了
3.不带哨兵位代码实现及思路
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
struct ListNode * lessnode = NULL,*lesstail = NULL;
struct ListNode *greatnode = NULL,*greattail = NULL;
struct ListNode * cur = pHead;
while(cur)
{
if(cur->val < x)
{
if(lesstail == NULL)
{
lessnode = lesstail = cur;
}
else
{
lesstail->next = cur;
lesstail = lesstail->next;
}
}
else
{
if(greattail == NULL)
{
greatnode = greattail = cur;
}
else
{
greattail->next = cur;
greattail = greattail->next;
}
}
cur = cur->next;
}
if(greattail)
{
greattail->next = NULL;;
}
if(lesstail)
{
lesstail->next = greatnode;
return lessnode;
}
else
{
return greatnode;
}
}
};
- 很明显,不带哨兵位需要的判断变多,也就意味着要考虑的东西也更多,并且尾插需要判空
- 大体过程与带哨兵位相似,需要注意的就是这几个条件语句,缺一不可
- 1.如果链表为{1,2,5,7,4},x为9,意味着链表的值都比x小,greatnode,greattail为空,所以要判断其是否为空
- 2.同样,如果链表为{7,4,9,10},x为5,意味着链表的值都比x大,lessnode,lesstail为空,所以需要判空
- 3.注意,如果lesstail为空,返回greatnode即可,lesstail不为空,那么返回lessnode