单项选择题 · 试读样题 2/25
考点:链表结构、指针连接与操作复杂度
【单选 02】 函数 removeElements 删除单链表中所有结点值等于 val 的结点,并返回新的头结点,其中链表头结点为 head ,则横线处填写( )。
// 结点结构体
struct Node {
int val;
Node* next;
Node() : val(0), next(nullptr) {}
Node(int x) : val(x), next(nullptr) {}
Node(int x, Node *next) : val(x), next(next) {}
};
Node* removeElements(Node* head, int val) {
Node dummy(0, head); // 哑结点,统一处理头结点
Node* cur = &dummy;
while (cur->next) {
if (cur->next->val == val) {
_______________________ // 在此填入代码
}
else {
cur = cur->next;
}
}
return dummy.next;
}
-
A
01 Node* del = cur;
02 cur = del->next;
03 delete del;
```
-
B
01 Node* del = cur->next;
02 cur->next = del;
03 delete del;
```
-
C
01 Node* del = cur->next;
02 cur->next = del->next;
03 delete del;
```
-
D
01 Node* del = cur->next;
02 delete del;
03 cur->next = del->next;
```
单项选择题 · 试读样题 3/25
考点:链表结构、指针连接与操作复杂度
【单选 03】 函数 hasCycle 采用Floyd快慢指针法判断一个单链表中是否存在环,链表的头节点为 head ,即用两个指针在链表上前进: slow 每次走 1 步, fast 每次走 2 步,若存在环, fast 终会追上 slow (相遇);若无环, fast 会先到达 nullptr,则横线上应填写( )。
struct Node {
int val;
Node *next;
Node(int x) : val(x), next(nullptr) {}
};
bool hasCycle(Node *head) {
if (!head || !head->next)
return false;
Node* slow = head;
Node* fast = head->next;
while (fast && fast->next) {
if (slow == fast) return true;
_______________________ // 在此填入代码
}
return false;
}
-
A
01 slow = slow->next;
02 fast = fast->next->next;
```
-
B
01 slow = fast->next;
02 fast = slow->next->next;
```
-
C
01 slow = slow->next;
02 fast = slow->next->next;
```
-
D
01 slow = fast->next;
02 fast = fast->next->next;
```