7.链表
7.1相交链表(简单)
题目描述:leetcode链接 160.相交链表
思路:
1.两个链表的头节点分别为headA和headB
2.令ListNode* A = headA,ListNode* B = headB
3.判断A、B是否相等
如果A != nullptr,则A = A -> next,否则A = headB;
如果B != nullptr,则B = B -> next,否则B = headA;
4.具体的遍历顺序如图所示,其中粉红色箭头是A的遍历顺序,绿色箭头是B的遍历顺序
举例说明:
见上图
若两链表不相交,则遍历完成后,A、B均为nullptr,return A即可
代码:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* A = headA;
ListNode* B = headB;
while (A != B) {
A = A != nullptr ? A -> next : headB;
B = B != nullptr ? B -> next : headA;
}
return A;
}
};
7.2反转链表(简单)
题目描述:leetcode链接 206. 反转链表
思路:
举例说明:
以上图为例,最后返回pre即可
代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while (cur) {
ListNode* temp = cur -> next;
cur -> next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
7.3回文链表(简单)
题目描述:leetcode链接 234. 回文链表
思路:
将链表内每个节点的值存储到vectot<int> res中,从res的两端向中间遍历,比较它们的值
举例说明:
如上图所示
代码:
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> res;
ListNode* cur = head;
while (cur) {
res.push_back(cur -> val);
cur = cur -> next;
}
for (int i = 0, j = res.size() - 1; i < j; i++, j--) {
if (res[i] != res[j]) return false;
}
return true;
}
};
7.4环形链表(简单)
题目描述:leetcode链接 141. 环形链表
思路:
1.使用快慢指针fast和slow,都从头指针head出发,fast每次走2步,slow每次走1步
2.由于fast相对于slow的相对速度为1,这意味着只要链表存在环,fast和slow最后一定会相遇
举例说明:
代码:
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast && fast -> next) {
fast = fast -> next -> next;
slow = slow -> next;
if (fast == slow) return true;
}
return false;
}
};
7.5环形链表II(中等)
题目描述:leetcode链接 142. 环形链表 II
思路:
leetcode l41.环形链表是判断链表是否存在环,本题则是需要寻找链表入环的第一个节点,相比leetcode l41.环形链表会需要多一些步骤才能实现。
假设fast和slow在相遇时分别走过的步数分别为f和s
可以看到,如果m>0,那么意味着在s = a + b 和 f = a + b + n * (b + c)时fast和slow就已经相遇了,所以m=0。即:
又由于f = 2 * s,所以 a + b + n * (b + c) = 2 * (a + b),a = c + (n - 1) * (b + c),也即当fast和slow相遇时,令ListNode* index1= head,ListNode* index2 = slow,当index1和index2走过a步之后,会相遇在环形链表的入口节点
举例说明:
见上图
代码:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast && fast -> next) {
fast = fast -> next -> next;
slow = slow -> next;
if (fast == slow) {
ListNode* index1 = head;
ListNode* index2 = slow;
while (index1 != index2) {
index1 = index1 -> next;
index2 = index2 -> next;
}
return index1;
}
}
return nullptr;
}
};