链表题目大汇总
1.链表反转acwing35
2.合并两个有序链表
3.链表的回文结构(判断一个链表是否是回文链表 较复杂) 牛客OR36
4.链表分割牛客CM11
5.两个链表的第一个公共结点AcWing 66
6.筛选链表AcWing 3756
7.重排链表 Acwing 3757 较综合
8.单链表快速排序Acwing 1451 旷视面试
1
.反转链表 这道题思路比较简单 本质就是将两个指针不断改变与赋值转换
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head -> next) return head;
auto p = head;
auto q = head -> next;
while(q){
auto o = q -> next;
q -> next = p;
p = q;
q = o;
}
head -> next = nullptr;
return p;
}
};
3 .链表的回文结构 核心 判断一个链表是不是回文先找到链表的中间节点中间节点往后全部反转
两个指针相互比较 一个头指针 一个尾指针
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
//核心 判断一个链表是不是回文
//先找到链表的中间节点 中间节点往后全部反转
// 两个指针相互比较 一个头指针 一个尾指针
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
//找到中间节点
auto dummy = new ListNode(-1);
dummy -> next = A;
auto fast = dummy;
auto slow = dummy;
while (fast && fast->next) {
fast = fast ->next -> next;
slow = slow -> next;
}
// 找实现链表反转
auto b = slow -> next;
auto p = slow -> next;
auto q = p -> next;
while(q){
auto o = q -> next;
q -> next = p;
p = q;
q = o;
}
b -> next = slow;
cout << p -> val << endl;
//开始比较
auto head = A;
auto tail =p;
//这里犯了致命错误 tail != head ......
while (tail != slow) {
if (tail-> val != head -> val) return false;
tail = tail-> next;
head = head -> next;
}
return true;
}
};