本文C++实现的关于双向链表的增删查改操作,收获颇多,第一篇博客请多指教。
- 定义节点类型
struct Number{
int data;
Number* next;
Number* previous;
};
- 定义一个链表类
class LinkList{
private:
Number *head;
Number *tail;
int length;
public:
LinkList();
void headInsert(int data);
void tailInsert(int data);
void display_HeadToTail();
void display_TailToHead();
Number * findNumber(int data);
void change(Number*);
void quit();
};
-
构造函数
LinkList::LinkList(){
head = NULL;
tail = head;
length = 0;
}
- 头插函数
void LinkList::headInsert(int data){
Number * node = new Number();
node->data=data;
if(head!=NULL){
head->previous=node;
node->next=head;
node->previous=NULL;
head=node;
}
else{
head=tail=node;
node->next=NULL;
node->previous=NULL;
}
length++;
}
- 尾插函数
void LinkList::tailInsert(int data){
Number * node = new Number();
node->data=data;
if(tail!=NULL){
tail->next=node;
node->previous=tail;
node->next=NULL;
tail=node;
}
else{
tail=head=node;
node->next=NULL;
node->previous=NULL;
}
length ++;
}
- 正序遍历
void LinkList::display_HeadToTail(){
Number *n = head;
if(length==0){
cout<<"No Number"<<endl;
return;
}
cout<<"length: "<<length<<endl;
cout<<"data: ";
while (n) {
cout<<n->data<<" ";
n = n->next;
}
cout << endl;
}
- 逆序遍历
void LinkList::display_TailToHead(){
Number *n = tail;
if(length==0){
cout<<"No Number"<<endl;
return;
}
cout<<"length: "<<length<<endl;
cout<<"data: ";
while (n) {
cout<<n->data<<" ";
n = n->previous;
}
cout << endl;
}
- 查找节点
Number * LinkList::findNumber(int data){
Number * n = head;
while (n) {
if(n->data==data)
return n;
n = n->next;
}
return NULL;
}
- 修改节点(可以将 findNumber 的返回值作为参数传入)
void LinkList::change(Number* node){
if(node==NULL)
{
cout<<"Number not exist"<<endl;
system("pause");
system("cls");
return;
}
int data;
cout<<"Enter a new data for "<<node->data<<" : ";
cin>>data;
system("cls");
node->data=data;
}
- 删除节点
void LinkList::deleteNumber(Number * n){
if(n==NULL){
cout<<"Node not exist"<<endl;
return;
}
if(n==head)
head=n->next;
else
n->previous->next=n->next;
if(n==tail)
tail=n->previous;
else
n->next->previous=n->previous;
n->next=NULL;
n->previous=NULL;
delete(n);
}
- 删除所有节点
void LinkList::quit(){
while(head){
deleteNumber(head);
}
head=tail=NULL;
length=0;
}
收获:
new和delete用法
malloc和free的用法