总结:链表专题
- 降低时间复杂度:空间换时间的方法
- 熟练掌握双指针算法:(思维的提升)快慢指针距离、达到的目的
- 思维的灵活使用:删除下一个结点
- 头结点方便处理边界问题
- 链表的边界问题要多试几个样例
- 链表与数组的灵活变换
- 画图考虑双指针的问题,列出关系表达式看具体的关系
面试题 02.01. 移除重复节点
思路一:空间换时间
class Solution {
public:
ListNode* removeDuplicateNodes(ListNode* head) {
auto p = head, q = head;
while (p) {
q = p;
while (q->next) {
if (q->next->val == p->val) q->next = q->next->next;
else q = q->next;
}
p = p->next;
}
return head;
}
};
面试题 02.02. 返回倒数第 k 个节点
class Solution {
public:
int kthToLast(ListNode* head, int k) {
auto p = head;
int cnt = 0;
while (p) p = p->next, cnt ++ ;
p = head;
for (int i = 0; i < cnt - k; i ++ ) p = p->next;
return p->val;
}
};
面试题 02.03. 删除中间节点
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};
面试题 02.04. 分割链表
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
auto sh = new ListNode(-1), lh = new ListNode(-1);
auto s = sh, l = lh;
while (head) {
if (head->val < x) {
s->next = head;
s = s->next;
}
else {
l->next = head;
l = l->next;
}
head = head->next;
}
l->next = NULL;
s->next = lh->next;
return sh->next;
}
};
面试题 02.05. 链表求和
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto dummy = new ListNode(-1);
auto cur = dummy;
int t = 0;
while (l1 && l2) {
int s = l1->val + l2->val + t;
t = s / 10;
auto p = new ListNode(s % 10);
cur = cur->next = p;
l1 = l1->next;
l2 = l2->next;
}
while (l1) {
int s = l1->val + t;
t = s / 10;
auto p = new ListNode(s % 10);
cur = cur->next = p;
l1 = l1->next;
}
while (l2) {
int s = l2->val + t;
t = s / 10;
auto p = new ListNode(s % 10);
cur = cur->next = p;
l2 = l2->next;
}
while (t) {
auto p = new ListNode(1);
cur = cur->next = p;
t = 0;
}
return dummy->next;
}
};
面试题 02.06. 回文链表
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> f;
while (head) {
f.push_back(head->val);
head = head->next;
}
int n = f.size();
for (int i = 0, j = n - 1; i < j; i ++ , j -- ) {
if (f[i] != f[j]) return false;
}
return true;
}
};
面试题 02.07. 链表相交
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
auto l = headA, r = headB;
while (l != r) {
l = l == NULL ? headB : l->next;
r = r == NULL ? headA : r->next;
}
return r;
}
};
面试题 02.08. 环路检测
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
auto s = head, f = head;
while (f) {
s = s->next;
f = f->next;
if (!f) {
return f;
}
f = f->next;
if (f == s) {
f = head;
while (f != s) {
f = f->next;
s = s->next;
}
return f;
}
}
return f;
}
};