solution.cpp 1.2 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
	int val;
	struct ListNode *next;
};
struct ListNode *partition(struct ListNode *head, int x)
{
	struct ListNode dummy;
	struct ListNode *prev1 = &dummy, *pivot;
	dummy.next = head;
	for (pivot = head; pivot != NULL; pivot = pivot->next)
	{
		if (pivot->val >= x)
		{
			break;
		}
		prev1 = pivot;
	}
	struct ListNode *p = pivot->next;
	struct ListNode *prev2 = pivot;
	while (p != NULL)
	{
		if (p->val < x)
		{
			prev2->next = p->next;
			p->next = prev1->next;
			prev1->next = p;
			prev1 = p;
			p = prev2->next;
		}
		else
		{
			prev2 = p;
			p = p->next;
		}
	}
	return dummy.next;
}
int main(int argc, char **argv)
{
	if (argc < 2)
	{
		fprintf(stderr, "Usage: ./test target n1 n2 n3...\n");
		exit(-1);
	}
	int i, target = atoi(argv[1]);
	struct ListNode *head = NULL;
	struct ListNode *prev = NULL;
	struct ListNode *p;
	for (i = 0; i < argc - 2; i++)
	{
		p = malloc(sizeof(*p));
		p->val = atoi(argv[i + 2]);
		p->next = NULL;
		if (head == NULL)
		{
			head = p;
			prev = head;
		}
		else
		{
			prev->next = p;
			prev = p;
		}
	}
	p = partition(head, target);
	while (p != NULL)
	{
		printf("%d ", p->val);
		p = p->next;
	}
	printf("\n");
	return 0;
}