前言
华为机试刷题
题目: HJ48 从单向链表中删除指定值的节点
编程语言: C++
解题状态: 磕磕绊绊
思路
非常综合的一道题目,涉及到链表的构建以及节点的删除。
代码
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(): val(0), next(nullptr) {}
ListNode(int x): val(x), next(nullptr) {}
ListNode(int x, ListNode* next): val(x), next(next) {}
};
void makeList(ListNode* head, int curVal, int preVal) {
ListNode* cur = head;
ListNode* insertNode = new ListNode(curVal);
while (cur->val != preVal) {
cur = cur->next;
}
ListNode* next = cur->next;
cur->next = insertNode;
insertNode->next = next;
}
void deleteNode(ListNode* head, int val) {
ListNode* cur = head;
while (cur) {
if (cur->val == val) {
if (cur->next == nullptr) {
cur = nullptr;
}
cur->val = cur->next->val;
cur->next = cur->next->next;
}
cur = cur->next;
}
}
int main() {
int n, headVal;
while (cin >> n >> headVal) { // 注意 while 处理多个 case
ListNode* head = new ListNode(headVal);
for (int i = 0; i < n; i++) {
int curV, preV;
cin >> curV >> preV;
makeList(head, curV, preV);
}
int remove;
cin >> remove;
deleteNode(head, remove);
ListNode* cur = head;
while (cur) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
return 0;
}