華為機試 HJ48-從單向鏈表中刪除指定值的節點
題目描述:
描述
輸入一個單向鏈表和一個節點的值,從單向鏈表中刪除等于該值的節點,
刪除后如果鏈表中無節點則返回空指針。
鏈表的值不能重復。
構造過程,例如輸入一行數據為:
6 2 1 2 3 2 5 1 4 5 7 2 2
則第一個參數6表示輸入總共6個節點,第二個參數2表示頭節點值為2,
剩下的2個一組表示第2個節點值后面插入第1個節點值,為以下表示:
1 2 表示為
2->1
鏈表為2->1
3 2表示為
2->3
鏈表為2->3->1
5 1表示為
1->5
鏈表為2->3->1->5
4 5表示為
5->4
鏈表為2->3->1->5->4
7 2表示為
2->7
鏈表為2->7->3->1->5->4
最后的鏈表的順序為 2 7 3 1 5 4
最后一個參數為2,表示要刪掉節點為2的值
刪除 結點 2
則結果為 7 3 1 5 4
數據范圍:鏈表長度滿足
1≤n≤1000 ,節點中的值滿足
0≤val≤10000
測試用例保證輸入合法
輸入描述:
輸入一行,有以下4個部分:
1 輸入鏈表結點個數
2 輸入頭結點的值
3 按照格式插入各個結點
4 輸入要刪除的結點的值
輸出描述:
輸出一行
輸出刪除結點后的序列,每個數后都要加空格
示例1
輸入:
5 2 3 2 4 3 5 2 1 4 3
輸出:
2 5 4 1
說明:
形成的鏈表為2->5->3->4->1
刪掉節點3,返回的就是2->5->4->1
示例2
輸入:
6 2 1 2 3 2 5 1 4 5 7 2 2
輸出:
7 3 1 5 4
說明:
如題
解題思路:
借助鏈表list的一些方法做查找、插入、刪除等操作,C++中可以使用STL中的list類。
C++實現代碼:
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main() {
int n;
list<int> myList;
while (cin >> n) { // 注意 while 處理多個 case
int head;
cin >> head;
myList.push_front(head);
int curVal, preVal;
for (int i = 1; i < n; i++) {
cin >> curVal >> preVal;
auto iter = std::find(myList.begin(), myList.end(), preVal);
if (iter != myList.end()) {
myList.insert(++iter, curVal);
}
}
int target;
cin >> target;
myList.remove(target);
// 輸出鏈表的每個值
for (auto iter = myList.begin(); iter != myList.end(); iter++) {
std::cout << *iter << " ";
}
std::cout << std::endl;
}
return 0;
}