leetcode-链表分割-14

题目要求
  现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
思路
  创建两个结点,一个用来存小于x的值,一个用于存储大于x的值,循环传进来的链表,不为空,就把链表的值和x进行比较,存入对应的新建的链表中,最后在小于x的链表之后续上大于x的链表,然后把两个链表的头结点释放。
图解
在这里插入图片描述
代码实现

class Partition {
public:
	ListNode* partition(ListNode* pHead, int x) {
		// write code here
		ListNode* cur = pHead;
		ListNode* shead, *stail, *mshead, *mtail;
		shead = (ListNode*)malloc(sizeof(ListNode));
		stail = shead;
		mshead = (ListNode*)malloc(sizeof(ListNode));
		mtail = mshead;
		stail->next = NULL;
		mtail->next = NULL;

		while (cur)
		{
			if (cur->val < x)
			{
				stail->next = cur;
				stail = stail->next;
			}
			else
			{
				mtail->next = cur;	
				mtail = mtail->next;
			}
			cur = cur->next;
		}
		stail->next = mshead->next;
		mtail->next = NULL;
		free(mshead);
		ListNode* h = (ListNode*)malloc(sizeof(ListNode));
		h = shead->next;
		free(shead);

		return h;
	}
};

猜你喜欢

转载自blog.csdn.net/weixin_43580319/article/details/113407896