特点:
常见技巧:
单链表结构:
struct ListNode {
ListNode *next;
int val;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
常见操作:
// 反转链表
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 判断链表是否有环
bool hasCycle(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
// 找环入口
ListNode* detectCycle(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
ListNode* p = head;
while (p != slow) {
p = p->next;
slow = slow->next;
}
return p;
}
}
return nullptr;
}
特点:后进先出(LIFO)
应用场景:
// 有效的括号
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
if (st.empty()) return false;
char top = st.top();
if ((c == ')' && top != '(') ||
(c == ']' && top != '[') ||
(c == '}' && top != '{')) {
return false;
}
st.pop();
}
}
return st.empty();
}
// 最小栈
class MinStack {
stack<int> dataStack;
stack<int> minStack;
public:
void push(int val) {
dataStack.push(val);
if (minStack.empty() || val <= minStack.top()) {
minStack.push(val);
}
}
void pop() {
if (dataStack.top() == minStack.top()) {
minStack.pop();
}
dataStack.pop();
}
int top() { return dataStack.top(); }
int getMin() { return minStack.top(); }
};
特点:先进先出(FIFO)
// 用栈实现队列
class MyQueue {
stack<int> inStack, outStack;
void transfer() {
while (!inStack.empty()) {
outStack.push(inStack.top());
inStack.pop();
}
}
public:
void push(int x) { inStack.push(x); }
int pop() {
if (outStack.empty()) transfer();
int val = outStack.top();
outStack.pop();
return val;
}
int peek() {
if (outStack.empty()) transfer();
return outStack.top();
}
bool empty() { return inStack.empty() && outStack.empty(); }
};
特点: