编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前 。

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

解题思路:
构造两个新的带头单向链表;将小于X的插到lessHead链表上,将大于等于X的插到greatHead链表上。最后合并两个链表,去掉带头结点。

/*
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
		ListNode* lessHead = (ListNode*)malloc(sizeof(ListNode));
		lessHead->next = NULL;
		ListNode* lessTail = lessHead;

		ListNode* greatHead = (ListNode*)malloc(sizeof(ListNode));
		greatHead->next = NULL;
		ListNode* greatTail = greatHead;

		ListNode* cur = pHead;

		while (cur)
		{
			if (cur->val<x)
			{
				lessTail->next = cur;
				lessTail = cur;
			}
			else
			{
				greatTail->next = cur;
				greatTail = cur;
			}
			cur = cur->next;
		}
		greatTail->next = NULL;
		lessTail->next = greatHead->next;

		ListNode* list = lessHead->next;
		free(lessHead);
		free(greatHead);
		return list;
	}
};
发布了37 篇原创文章 · 获赞 0 · 访问量 1319

猜你喜欢

转载自blog.csdn.net/smilevampire/article/details/104086978