Leetcode每日一题:86.partition-list(分割列表)

在这里插入图片描述
思路:把一个链表分成两个链表,小于x的为一个,大于等于x的为一个,分割完后将两链表进行连接;只是在链表的创建,以及最后首结点的返回需要多加判定条件,要注意一下;
在这里插入图片描述

struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

ListNode *partition(ListNode *head, int x)
{
	if (head == NULL)
	{
		return NULL;
	}
	//分成两个链表
	ListNode *h1 = NULL, *h2 = NULL; //h1用于生成小于x的链表,h2用于生成大于等于x的链表
	ListNode *h3 = NULL, *h4 = NULL; //h3指向小于x的链表的头节点,h4指向大于等于x的链表的头节点
	bool flag1 = true, flag2 = true; 
	while (head)
	{
		if (head->val < x)
		{
			ListNode *temp = new ListNode(head->val);
			if (flag1)  //如果是首个结点,单独操作
			{
				h1 = temp;
				h3 = h1;
				flag1 = false;
			}
			else
			{
				h1->next = temp;
				h1 = temp;
			}

			head = head->next;
		}
		else
		{
			ListNode *temp = new ListNode(head->val);

			if (flag2) //如果是首个结点,单独操作
			{
				h2 = temp;
				h4 = h2;
				flag2 = false;
			}
			else
			{
				h2->next = temp;
				h2 = temp;
			}

			head = head->next;
		}
	}
	if (h1 == NULL) //如果小于x的链表为空,直接返回h4即可;
	{
		return h4;
	}
	else if (h2 == NULL) //如果大于等于x的链表为空,直接返回h3即可,不用连接两个链表;
	{
		return h3;
	}
	else
	{
		h1->next = h4;
		h2->next = NULL;
		return h3;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值