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;
}