数据结构学习

链表问题总结:

单链表逆置:

void TurnDlist(PDlist plist) {
	assert(plist != NULL);
	if (plist->head->next != NULL) {
		DNode* curr = plist->head;
		DNode* pre = NULL;
		while (curr!= NULL) {
			DNode* temp = curr->next;
			curr->next = pre;
			pre = curr;
			curr = temp;
		}
		plist->head = pre;
	}
}

判断单链表是否有环:

bool IsCycle(PDlist plist) {
	assert(plist != NULL);
	DNode* fast = plist->head;
	DNode* slow = plist->head;
	if (plist->head != NULL && plist->head->next != NULL) {
		while (fast->next != NULL) {
			fast = fast->next->next;
			slow = slow->next;
			if (fast == slow) {
				return true;
			}
		}
		return false;
	}
	else
	{
		return false;
	}
}

有环找入口:

DNode* GetNode(PDlist plist) {
	assert(plist != NULL);
	if (IsCycle(plist)) {
		DNode* fast = plist->head;
		DNode* slow = plist->head;
		while (fast->next != NULL) {
			fast = fast->next->next;
			slow = slow->next;
			if (fast == slow) {
				break; 
			}
		}

		
		if (fast == NULL || fast->next == NULL) {
			return NULL; 
		}

		fast = plist->head;
		while (fast != slow) {
			fast = fast->next;
			slow = slow->next;
		}

		return fast;
	}

}

两个单链表合并:

void MergeDlist(PDlist p1, PDlist p2) {
	assert(p1 != NULL && p2 != NULL);
	if (p1->head == NULL) {
		p1->head = p2->head;
	}
	else {
		DNode* curr = p1->head;
		while (curr->next != NULL) {
			curr = curr->next;
		}
		curr->next = p2->head;
	}
}

输出倒数第k个节点的值:

void PrintNode(PDlist plist, int k) {
	assert(plist != NULL);
	if (k <= 0 || plist->head == NULL) {
		return;
	}
	else {
		DNode* fast = plist->head;
		DNode* slow = plist->head;
		int count = 1;
		while (count < k&&fast!=NULL) {
			fast = fast->next;
			count++;
		}
		if (fast == NULL) {
			return;
		}
		else {
			while (fast->next != NULL) {
				fast = fast->next;
				slow = slow->next;
			}
			printf("%d", slow->val);
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值