当前位置:网站首页>(practice C language every day) reverse linked list II

(practice C language every day) reverse linked list II

2022-07-06 06:34:00 Yi Xiaoxia

Reverse a linked list II

Give you the head pointer of the single linked list  head  And two integers  left  and  right , among  left <= right . Please reverse from position  left  To the position  right  The linked list node of , return   Inverted list  .

Example 1:

 Input :head = [1,2,3,4,5], left = 2, right = 4
 Output :[1,4,3,2,5]

Example 2:

 Input :head = [5], left = 1, right = 1
 Output :[5]

Tips :

  • The number of nodes in the linked list is  n
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

The following program realizes this function :

#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;
}
原网站

版权声明
本文为[Yi Xiaoxia]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132019052234.html