栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构--单向链表的代码实现(c++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构--单向链表的代码实现(c++)

1.链表构造 节点构造:
template 
struct node{
    type val;
    node *next;
    node() {next=NULL;}
    node(type &x,type *p){val=x;next=p;}
};
链表构造:
template 
class list{
    public:
    node *head;//头结点;
    list(){head=new node;}
    int Length();
    bool Empty();
    void Clear();
    void Traverse(void(*visit)(const type &e));
    bool Get_value(int pos,type &e);
    bool Set_value(int pos,type &e);
    bool Insert(int position, const type &x);
    bool Delete(int pos);
    node* get_ptr(int position);
};
2.函数实现 2.1 链表长度
template 
int list::Length(){
    int count=0;
    node *temp_ptr;
    for (temp_ptr=head->next;temp_ptr!=NULL;temp_ptr=temp_ptr->next) counr++;
    return count;
}
2.2 判断链表是否为空
template 
bool list::Empty(){
    return head->next==NULL;
}
2.3 清空链表
template 
bool list::Empty(){
    return head->next==NULL;
}
2.4 对每个元素调用函数(*visit)
template 
void list::Traverse(void (*visit)(const type &e)){
    node *temp_ptr;
    for (temp_ptr=head->next;temp_ptr!=NULL;temp_ptr=temp_ptr->next){
        (*visit)(temp_ptr->val);
    }
}
2.5 取得元素值

将位置为pos的元素值赋值给e,如果位置不合理就返回false,合理返回true。

template 
bool list::Get_value(int pos,type &e){
    if (pos<1||pos>Length()) return false;
    node *temp_pos=get_ptr(pos);
    e=temp_pos->val;
    return true;
}
2.6 设置元素值
template 
bool list::Set_value(int pos,type &e){
    if (pos<1||pos>Length()) return false;
    node *temp_ptr=Get_ptr(pos);
    temp_ptr->val=e;
    return true;
}

2.7 插入元素值
template 
bool list::Insert (int position, const type &x){
    if (pos<1||pos>Length()+1) return false;
    node *temp_ptr=Get_ptr(position-1);
    node *new_ptr=new node(temp_ptr->next,x);
    temp_ptr->next=new_ptr;
    return true;
}

2.8 删除元素
template 
bool list::Delete(int pos){
    if (pos<1||pos>Length()) return false;
    node *pre_pos,*next_pos;
    pre_pos=Get_ptr(pos-1);
    next_pos=Get_ptr(pos);
    pre_pos->next=next_pos->next;
    delete next_pos;
    return true;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/316871.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号