网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

C++  数据结构链表的实现代码

C++ 链表

成都创新互联主营海淀网站建设的网络公司,主营网站建设方案,app软件定制开发,海淀h5小程序定制开发搭建,海淀网站营销推广欢迎海淀等地区企业咨询

之前一直没怎么在意C++中的链表,但是突然一下子让自己写,就老是出错。没办法,决定好好恶补一下该方面的知识,也为今后的数据结构大下个良好的基础,于是我总结出以下几点,有些地方可能不正确,还望大家不吝赐教,旨在共同进步。

总结:

1、链表List的基本单元是节点Node,因此想要操作方便,就必须为每一步打好基础,Node的基本结构如下:

class Node{
public:
  int data;
  Node *next;
  Node(int da=0,Node *p=NULL){
    this->data=da;
    this->next=p;
  }
};

我们可以看出,Node的成员变量一共有两个,都是public,因为我们要对这两个变量进行操作,所以不能是private类型的。然后是一个构造函数,第二个参数默认值为NULL,也就是说如果我们创建新节点时只指定第一个参数,而不写第二个参数,那么它默认的就是NULL,以这种方式可以更灵活的使用Node,个人建议这么使用哦。

2、第二步就是创建我们的链表了,同样我们这里先给出链表的代码,在进行一一的解释。

class List{
private:
  Node *head,*tail;
  int position;
public:
  List(){head=tail=NULL;};
  ~List(){delete head;delete tail;};
  void print();
  void Insert(int da=0);
  void Delete(int da=0);
  void Search(int da=0);
};

我们这里面有两个数据类型,一个是Node。另一个是指代节点位置的成员变量(起不到什么作用,且不去管它吧)。使用head和tail来命名便是为了见名知意,使操作更加准确。然后是重要的六个函数,各自的功能不言而喻咯,其实最重要的是在每一个函数中我们都默认能操作head和tail两个成员变量,这样能简化我们的参数列表,使得函数更加优雅。

下面是我的一个单链表的实现,包含创建链表,插入值,删除特定的值,查找特定值得在链表中的位置。

#include
using namespace std;

class Node{
public:
  int data;
  Node *next;
  Node(int da=0,Node *p=NULL){
    this->data=da;
    this->next=p;
  }
};

class List{
private:
  Node *head,*tail;
  int position;
public:
  List(){head=tail=NULL;};
  ~List(){delete head;delete tail;};
  void print();
  void Insert(int da=0);
  void Delete(int da=0);
  void Search(int da=0);
  int getValueAt(int position);
  void setValueAt(int position,int da);
};

int List::getValueAt(int position){
  Node *p=head;
  if(p==NULL){
    cout<<"The List is Empty!"<next;
    }
    if(p==NULL){
      cout<<"There is no value of this position in this List!"<data<data;
}

void List::setValueAt(int position,int da){
  Node *p=head;
  if(p==NULL){
    cout<<"The List is Empty!"<next;
    }
    if(p==NULL){
      cout<<"There is No Position in this List!"<data=da;
      cout<<"The Value in this position has been Updated!"<data!=da){
    p=p->next;
    count++;
  }
  cout<<"the value you want to search is at position %d"<data!=da){
    q=p;
    p=p->next;
  }
  q->next=p->next;
  cout<<"The Deletion Operation had been finished!"<next=NULL;
    tail->next=NULL;
  }else{
    Node *p=new Node(da);
    tail->next=p;
    tail=p;
    tail->next=NULL;
  }

}

void List::print(){
  Node *p=head;
  while(p!=NULL){
    cout<data<<" \a";
    p=p->next;
  }
  cout<

下面是代码运行后的结果:

C++  数据结构链表的实现代码

好了,单链表的基本操作大致就是这样了,希望我们都能从中有所收获。如果您发现代码中有什么错误,还望不吝赐教,让我们共同进步吧。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


文章题目:C++  数据结构链表的实现代码
网站地址:http://bjjierui.cn/article/pigedj.html

其他资讯