链表反转----链表判断是否有环

1. 链表反转

#include <iostream>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <list>
#include <algorithm>
using namespace std;

/*
链表反转
1. 注意用一个变量存储cur节点的下一个结点,不要断链即可
*/
struct ListNode
{
	ListNode *next;
	int val;
	ListNode(int x) : val(x), next(nullptr) {}
};

ListNode *reverList(ListNode *head)
{
	if (head == nullptr)
		return nullptr;
	ListNode *pre = head;
	ListNode *cur = head->next;
	ListNode *post = nullptr;
	while (cur != nullptr)
	{
		post = cur->next;
		cur->next = pre;
		pre = cur;
		cur = post;
	}
	return pre;
}
int main()
{
	
	ListNode *p = new ListNode(1);
	ListNode *p1 = new ListNode(2);
	ListNode *p2 = new ListNode(3);
	ListNode *p3 = new ListNode(4);
	p->next = p1;
	p1->next = p2;
	p2->next = p3;

	ListNode *res = reverList(p);
	for (int i = 0; i < 4; ++i)
	{
		cout << res->val << " ";
		res = res->next;
	}
	cout << endl;
	system("pause");
	return 0;
}

2. 判断链表是否有环

#include <iostream>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <list>
#include <algorithm>
using namespace std;

/*
链表有环
1. 是否存在环:一个走一步,一个走两步,判断是否会相遇
2. 找出环的入口:分别用一个指针(ptr1, prt2),同时从head与slow和fast的相遇点出发,
				 每一次操作走一步,直到ptr1 == ptr2,此时的位置也就是入口点
*/
struct ListNode
{
	ListNode *next;
	int val;
	ListNode(int x) : val(x), next(nullptr) {}
};

bool ifCircle(ListNode *head)
{
	if (head == nullptr)
		return 0;
	ListNode * fast = head;	//每次走两步
	ListNode * slow = head;	//每次走一步
	while (fast != nullptr && fast->next != nullptr)
	{
		slow = slow->next;
		fast = fast->next->next;
		if (slow == fast)
			return true;//有环
	}
	return false;
}

ListNode* circleStart(ListNode *head)
{
	if (head == nullptr)
		return nullptr;
	ListNode * fast = head;	//每次走两步
	ListNode * slow = head;	//每次走一步
	while (fast != nullptr && fast->next != nullptr)
	{
		slow = slow->next;
		fast = fast->next->next;
		if (slow == fast)
			break;//有环
	}
	if (fast == nullptr && fast->next == nullptr)
		return nullptr;

	ListNode *ptr1 = head;
	ListNode *ptr2 = slow;
	while (ptr1 != ptr2)
	{
		ptr1 = ptr1->next;
		ptr2 = ptr2->next;
	}
	return ptr1;
}

int main()
{
	ListNode *p = new ListNode(1);
	ListNode *p1 = new ListNode(2);
	ListNode *p2 = new ListNode(3);
	ListNode *p3 = new ListNode(4);
	p->next = p1;
	p1->next = p2;
	p2->next = p3;
	p3->next = p2;

	int res = ifCircle(p);
	cout << res << endl;

	ListNode *ans = circleStart(p);
	cout << ans->val << endl;

	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值