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

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值