C++中list雙向鏈表中滿足條件的任意位置刪除

C++中list雙向鏈表中滿足條件的任意位置刪除

鏈表中的節點包含數據和前一個或者下一個節點的地址,這樣對鏈表的處理就比數組要麻煩很多。而在C++中有一個頭文件可以實現雙向鏈表,叫做。裏面包含了一些鏈表的基本操作。我們就舉幾個例子。

list<int> a;//建立空鏈表
	a.push_back(2);//鏈表末尾插入2
	a.push_front(3);//鏈表前面插入3
	a.erase(a.begin());//刪除鏈表第一個節點
	a.remove(1);//移除所有數據爲1的節點
	a.insert(a.begin(), 2);//在鏈表首插入2

對鏈表中間部分的刪除是比較麻煩的,雖然在list中不需要考慮鏈表的地址連接,但是刪除給定條件的數據還是非常麻煩的。我們需要對滿足條件的鏈表節點進行刪除操作,如果在迭代器中直接使用erase()和remove()進行操作就會破壞鏈表的結構,直接改變鏈表的大小,無法繼續運行。

		for (iterator1 = test.begin(); iterator1 != test.end(); iterator1++) 
			if (*iterator1 == 2) test.erase(iterator1);

運行結果:刪除符合要求的數據後,迭代器無法指向下一個節點,造成鏈表的不完整
刪除符合要求的數據後,迭代器無法指向下一個節點,造成鏈表的不完整
所以,我們需要使用迭代器而不破壞鏈表結構,還要進行刪除操作,就可以將查找和刪除分開。如下圖所示。

#include<iostream>
#include<list>
using namespace std;
int main()
{
	list<int> test;//建立一個鏈表
	list<int>::iterator iterator1;//迭代器,用於遍歷鏈表
	list<int>::iterator iterator2;
	test.push_back(1);
	test.push_back(2);
	test.push_front(3);
	test.push_front(3);
	test.push_front(4);
	test.push_back(6);//433126,生成的鏈表數據
	//實現功能:如果鏈表相鄰接點數據相等,則刪除.
	//方法:查找賦空,最後移除
	iterator2 = test.begin();
	iterator2++;
	for(iterator1=test.begin();iterator1 !=test.end();iterator1++){
		if (*iterator2 == *iterator1) { *iterator2 = NULL; *iterator1 = NULL; }
		iterator2++;
		if(iterator2==test.end()) break;
	}
	test.remove(NULL);
	//輸出:4126
	for (iterator1 = test.begin(); iterator1 != test.end(); iterator1++) {
         cout << *iterator1 << ' ';
	      }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章