0
点赞
收藏
分享

微信扫一扫

(自用)单链表中的循环移位问题

承蒙不弃 2022-03-11 阅读 79

最开始的想法:每次移位都把尾元素移到头元素,但这样的话for循环里又需要一个while循环:

void Move(node* H) {
	node* temp, * pend, * head;
	int direction, step;
	scanf("%d", &direction);
	scanf("%d", &step);
	if (direction) {
		for (int i = 0; i < step; i++) {
			pend = H;
			head = H->next;
			while (pend->next->next)
				pend = pend->next;
			temp = pend->next;
			pend->next = NULL;
			H->next = temp;
			temp->next = head;
		}
	}
	else {
		for (int i = 0; i < step; i++) {
			head = H->next->next;
			temp = H->next;
			pend = H;
			while (pend->next)
				pend = pend->next;
			H->next = head;
			pend->next = temp;
			pend = pend->next;
			pend->next = NULL;
		}
	}
}

复杂度会是O(n²),于是博采众长一番,做如下改进:

void Move(node* H, int n) {
	node* temp, * pend, * head;
	int direction, step;
	temp = (node*)malloc(sizeof(node));
	scanf("%d", &direction);
	scanf("%d", &step);
	int i = 0;
	pend = H;
	if (direction) {
		while (pend->next) {
			pend = pend->next;
			i++;
			if (i == n - step) {
				temp = pend->next;
				pend->next = NULL;
			}
		}
	}
	else {
		while (pend->next) {
			pend = pend->next;
			i++;
			if (i == step) {
				temp = pend->next;
				pend->next = NULL;
			}
		}
	}
	head = H->next;
	H->next = temp;
	while (temp->next)
		temp = temp->next;
	temp->next = head;
}

 把要移到头部的几个尾元素一起移动,这样就只需要一个循环就能完成。并且左移和右移操作的区别只用i来区分,其他操作都一样,可谓是非常的多态

举报

相关推荐

0 条评论