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

第五章 模板与群体数据(3)

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

第五章 模板与群体数据(3)

顺序访问的线性群体 -- 链表

链表就不进行说明了,直接上模板

单链表的结点模板
template 
class Node {
private:
    Node *next;
public:
    T data;    // 理论放到 private
    Node(const T& item, Node *next = 0);
    void insertAfter(Node *p);
    Node *deleteAfter();
    Node *nextNode() const;
};

template 
Node::Node(const T& data, Node *next = 0):data(data), next(next) {}

template 
Node *Node::nextNode() {
    return next;
}

template 
void Node::insertAfter(Node *p) {
    p->next = next;
    next = p;
}

template 
Node *Node::deleteAfter(void) {    // 删除操作还要返回是有时需要继续操作删除的结点
    Node *tempPtr = next;
    if(next == 0)
        return 0;
    next = tempPtr->next;
    
    return tempPrt;
}

链表类示例

使用 STL 库的链表类模板

从键盘输入 10 个整数,用这些整数生成一个链表,按顺序输出链表中结点的数值。

输入一个待查找整数,在链表中查找该整数,删除所在结点,输出链表

程序结束时清空链表

#include 
#include "LinkedList.h"
using namespace std;

int main() {
    LinkedList list;
    // 1
    for(int i=0; i<10; i++) {
        int item;
        cin >> item;
        list.insertFront(item);
    }
    cout << "List : ";

    list.reset();
    while(! list.endOfList() ) {
        cout << list.data() << " ";
        list.next();
    }
    cout << endl;

    // 2
    int key;
    cout << "Please enter some integer neeeded to be deleted: ";
    cin >> key;
    
    list.reset();
    while(! list.endOfList() ) {
        if(list.data() == key)
            list.deleteCurrent();
        list.next();
    }
    cout << "list : ";
    
    // 3
    list.reset();
    while(! list.endOfList() ) {
        cout << list.data() << " ";
        list.next();
    }
    cout << endl;

    return 0;
}

 

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

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

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