solution.cpp 1.0 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
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
	int val;
	struct ListNode *next;
};
static struct ListNode *reverseBetween(struct ListNode *head, int m, int n)
{
	int i;
	struct ListNode dummy;
	struct ListNode *prev = &dummy;
	prev->next = head;
	for (i = 1; i < m; i++)
	{
		prev = prev->next;
	}
	struct ListNode *p = prev->next;
	for (i = m; i < n; i++)
	{
		struct ListNode *q = p->next;
		p->next = q->next;
		q->next = prev->next;
		prev->next = q;
	}
	return dummy.next;
}
int main(int argc, char **argv)
{
	if (argc < 3)
	{
		fprintf(stderr, "Usage: ./test m n 1 2 3...\n");
		exit(-1);
	}
	int i, count = argc - 3;
	struct ListNode dummy;
	struct ListNode *prev = &dummy;
	struct ListNode *p;
	for (i = 0; i < count; i++)
	{
		p = malloc(sizeof(*p));
		p->val = atoi(argv[i + 3]);
		p->next = NULL;
		prev->next = p;
		prev = p;
	}
	int m = atoi(argv[1]);
	int n = atoi(argv[2]);
	struct ListNode *head = reverseBetween(dummy.next, m, n);
	for (p = head; p != NULL; p = p->next)
	{
		printf("%d ", p->val);
	}
	printf("\n");
	return 0;
}