您的位置:首页 > 其它

在双向链表中删除指定元素

2013-04-01 14:03 363 查看
#include <iostream>
using namespace std;

class List {
public:
List(int num) {
this->num = num;
}
int num;
List* next;
List* pre;
};
//创建链表
List* createList(int count) {
if(count == 0 ) return NULL;
List* list = new List(0);
List* cur = list;
cur->pre = NULL;
List* pre = list;
for(int i=1; i < count ; i++) {
cur->next = new List(i);
cur = cur->next;
cur->pre = pre;
pre = cur;
}
cur->next = NULL;
return list;
}
//双向遍历
void travelList(List* list) {
List* cur = list;
List* end;
while(cur != NULL) {
cout<<cur->num<<endl;
if(!cur->next)
end = cur;
cur = cur->next;
}

cur = end;
while(cur != NULL) {
cout<<cur->num<<endl;
cur = cur->pre;
}
}

List* remove(List* head,List* nodeToDelete){
List* cur = head;
while(cur && cur != nodeToDelete) {
cur = cur->next;
}
if(!cur)
return head;
List* pre = cur->pre;
List* post = cur->next;
if(pre)
pre -> next = post;
if(post)
post -> pre = pre;
List* ret = head;
if(cur == head)
ret = post;
delete cur;
return ret;

}
int main(){
List* l = createList(10);
travelList(l);
l=remove(l,l->next->next);
cout<<endl;
travelList(l);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息