本文将根据自己对数据结构的理解,介绍数据结构的基本类型--链表。写的不好的地方欢迎指正。首先是单链表。
结点数据结构定义:
struct node{
int data;
node* next;
}
单链表的基本操作:
1、确定链表长度:
int length(node* first) const{
node* current=first;
int len=0;//链表长度初始值置0while(current){
len++;current=current->next;
}
delete current;
return len;
}
2、插入元素
bool insert(node* first,int x,int y){//将y插入单链表first值为y的结点后,插入成功返回true,否则返回false
node* current=first;
while(current!=null&¤t->data!=y){//查找插入位置
current=current->next;
}
if(current!=null)//找到插入的位置{
node* p=new node;
p->data=x;
p->next=current->next;
current->next=p;
return true;
}
return false;
}
3、删除元素
bool delete(node* first,int x){//删除链表中值为x的结点,删除成功返回true
node* current=first,pre=current;
while(current!=null&¤t->data!=x){//查找值为x的结点
pre=current;current=current->next;
}
if(current==null){
cout<<"无此结点!"<<endl;
return false;
}
else{
pre->next=current->next;
return true;
}
}
现在介绍双链表
首先也是结点结构定义:
struct node2{
int data;
node2* next;
node2* pre;
}
然后是基本操作:
1、插入元素
bool insert(node2* first,int x,int y){//将x插入值为y的结点后,插入成功返回true
if(first->data==y){
node2* p=new node;
p->data=x;
p->next=first->next;p->pre=first;
first->next->pre=p;first->next=p;
return true;
}
node2* current=first->next;
while(current!=first&¤t->data!=y){
current=current->next;
}
if(current==first)
return false;
else{
node2* p=new node;
p->data=x;
p->next=current->next;p->pre=current;current->next->pre=p;current->next=p;
return true;
}
}
2、删除元素
bool delete(node2* first,int x){
if(first->data==x){
first->pre->next=first->next;
first->next->pre=first->pre;
first=first->next;
return true;
}
node2* current=first->next;
while(current!=first&¤t->data!=x)
current=current->next;
if(current==first)
return false;
else{
current->pre->next=current->next;
current->next->pre=current->pre;
delete current;
return true;
}
}