LeetCode10: 分割链表

分割链表

编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x,
x 只需出现在小于 x 的元素之后(如下所示)。分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。
示例 :
输入 : head = 3->5->8->5->10->2->1, x = 5
输出 : 3->1->2->10->5->5->8.

解题思路:
第一步:先将小于x的链表放一起,大于X的链表放一起
第二步:将两个链表进行整合到一起

struct ListNode* partition(struct ListNode* head, int x){
	struct ListNode* LH, *LT, *GH, *GT, *cur;
	if (head == NULL) {
		return NULL;
	}
	LH = LT = (struct ListNode*)malloc(sizeof(struct ListNode));
	GH = GT = (struct ListNode*)malloc(sizeof(struct ListNode));
	cur = head;
	while (cur) {
		if (cur->val < x) {
			LT->next = cur;
			LT = LT->next;
		}
		else {
			GT->next = cur;
			GT = GT->next;
		}
		cur = cur->next;
	}
	GT->next = NULL;
	LT->next = GH->next;
	LT = LH;//只是单纯的释放内存空间,
	GT = GH;
	LH = LH->next;
	free(LT);
	free(GT);
	return LH;
}
 
struct ListNode* partition(struct ListNode* head, int x){
	struct ListNode* smallhead, *bighead, *cur;
	smallhead = (struct ListNode*)malloc(sizeof(struct ListNode));//smallhead 只是虚拟的头结点
	bighead = (struct ListNode*)malloc(sizeof(struct ListNode));  //bighead  只是虚拟的节点
	struct ListNode*  small = smallhead;//刚开始头结点和虚拟头结点都指定在同一个位置,
	struct ListNode*  big = bighead;
	cur = head;
	if (head == NULL) {
		return NULL;
	}
	//完成比较的真正步骤
	while (cur) { 
		if (cur->val < x) {
			small->next = cur;
			small = small->next;
		}
		else {
			big->next = cur;
			big = big->next;
		}
		cur = cur->next;
	}
	big->next = NULL;
	small->next = bighead->next;//让小于x的节点排在大于x 的节点的前面
	small = smallhead->next;//事实上smallhead 的下一个节点才是该链表的真正的节点
	free(bighead);
	free(smallhead);
	return small;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值