【LeetCode】86. Partition List

题目:

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to 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的结点之前,要求两部分中元素的相对次序保持不变。

 

分析:

链表的基本操作,使用尾插法,注意不要断链。

 

代码:(时间复杂度O(n),n为结点的个数)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode* partition(ListNode* head, int x) {
		ListNode *my_head = new ListNode(0);
		ListNode *my_tail = my_head;
		ListNode *bigger_head = new ListNode(0);
		ListNode *bigger_tail = bigger_head;
		
		my_head->next = head;
		
		while (my_tail->next) {
			if (my_tail->next->val < x) {
				my_tail = my_tail->next;
			} else {
				bigger_tail->next = my_tail->next;
				bigger_tail = bigger_tail->next;
				my_tail->next = bigger_tail->next;
				bigger_tail->next = nullptr;
			}
		}
		my_tail->next = bigger_head->next;
		delete bigger_head;
		
		return my_head->next;
	}
};

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页