【LeetCode】86. Partition List(C++)

地址:https://leetcode.com/problems/partition-list/

题目:

Given a linked list and a value x x x, partition it such that all nodes less than x x x come before nodes greater than or equal to x x x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

理解:

给了一个链表,一个x,要求把这个链表分为两部分,前面是小于x的,后面是大于等于x的,且不能改变原来的相对顺序。

实现:

lessPre:小于部分的尾指针
morePre:大于等于部分的尾指针
lessHead:小于部分的头指针
moreHead:大于等于部分的头指针

class Solution {
public:
	ListNode* partition(ListNode* head, int x) {
		ListNode* lessPre = nullptr;
		ListNode* morePre = nullptr;
		ListNode* lessHead = nullptr;
		ListNode* moreHead = nullptr;
		ListNode* p = head;
		while (p) {
			if (p->val < x) {
				if (!lessHead) {
					lessHead = p;
					lessPre = p;
				}
				else {
					lessPre->next = p;
					lessPre=lessPre->next;
				}
			}
			else {
				if (!moreHead) {
					moreHead = p;
					morePre = p;
				}
				else {
					morePre->next = p;
					morePre = morePre->next;
				}
			}
			p = p->next;
		}
		if (lessHead) {
			lessPre->next = moreHead;
			if(moreHead)
				morePre->next = nullptr;
			return lessHead;
		}
		else if (moreHead) {
			morePre->next = nullptr;
			return moreHead;
		}
		else
			return nullptr;
	}
};

可以考虑用带头结点的链表,能够简化很多操作。

class Solution {
public:
	ListNode* partition(ListNode* head, int x) {
		ListNode* lessHead = new ListNode(0);
		ListNode* moreHead = new ListNode(0);
		ListNode* lessPre = lessHead;
		ListNode* morePre = moreHead;
		ListNode* p = head;
		while (p) {
			if (p->val < x) {
					lessPre->next = p;
					lessPre=lessPre->next;
			}
			else {
				morePre->next = p;
				morePre = morePre->next;	
			}
			p = p->next;
		}
		lessPre->next = moreHead->next;
		morePre->next = nullptr;
		return lessHead->next;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值