c语言双向链表的代码6,C语言双向链表-代码.doc

C语言双向链表-代码

建立双向链表 实现对双向链表的插入 删除操作·

#include

using std::cout;

using std::endl;

template class Node{ //节点的定义

public:

Node(T t):item(t),previous(0),next(0){}

T item;

Node* previous;

Node* next;

};

template class TwoWayLinkedList{ //双向链表的定义

public:

TwoWayLinkedList():length(0),head(0),tail(0){};

~TwoWayLinkedList();

int getLength(){return length;}

void add(T t);

T get(int i);

void insert(int i,T t);

void del(int i);

void display();

private:

Node* head;

Node* tail;

int length;

};

template void TwoWayLinkedList::add(T t){ //在链表的结尾添加新元素

if(head==0){ //如果链表为空

head=new Node(t);

tail=head;

}

else {

Node* q=new Node(t); //新建一个节点储存新元素

tail->next=q; //加到当前链表的结尾

q->previous=tail; //它的前者为当前的结尾

tail=tail->next; //把结尾移到这个新元素

}

length++;

}

template T TwoWayLinkedList::get(int i){ //返还下标为i的元素

if(i>=length||i<0) return 0; //如果没有这个下标返还0

int j=0;

Node* p=head;

while(j

p=p->next;

j++;

}

T item=(p->T);

return item;

}

template void TwoWayLinkedList::insert(int i, T t){ //在下标为i处插入一个新元素

if(i<=0){ //如果下标小于等于0,插在最前面

Node* p=new Node(t);

p->next=head;

head->previous=p;

head=p;

length++;

}

else if(i>=length) add(t); //如果下标大于最大下标加在最后面

else{

Node* n=new Node(t);

int j=0;

Node* t=head;

while(j

t=t->next;

j++;

}

n->next=t->next;

n->previous=t;

(t->next)->previous=n;

t->next=n;

length++;

}

}

template void TwoWayLinkedList::del(int i){ 删除下标为i的元素

if(i<0||i>=length) return; // 如果没有这个下标直接退出

else{

if(length==0) return; //如果链表为空推出

else if(length==1){ //如果只有一个元素

delete head;

head=0;

tail=0;

}

else if(i==0){ // 如果要删除第一个元素

Node* t=head;

head=head->next; //把第一个移至下一个

head->previous=0;

delete t;

}

else if(i==length-1){ //如果要删除最后一个元素

Node* t=tail;

tail=tail->previous; //把最后一个往前移动一位

tail->next=0;

delete t;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值