数据结构--C++

来源:互联网 发布:阿里专有云asp csp 编辑:程序博客网 时间:2024/06/06 12:35

本文将根据自己对数据结构的理解,介绍数据结构的基本类型--链表。写的不好的地方欢迎指正。首先是单链表。

结点数据结构定义:

struct    node{

int data;

node* next;

}

单链表的基本操作:

1、确定链表长度:

   int  length(node*  first)  const{

   node* current=first;

    int len=0;//链表长度初始值置0

while(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&&current->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&&current->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&&current->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&&current->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;

}

}


0 0
原创粉丝点击