首页 / C++ / C++链表,尽量使用C++11
C++链表,尽量使用C++11
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++链表,尽量使用C++11,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2829字,纯文字阅读大概需要5分钟。
内容图文
原创,转载请注明出处。
为了熟悉vs环境、c++中的类写的链表
chainNode.h:
#pragma once
#include<memory>
#ifndef CHAINNODE_H
#define CHAINNODE_H
using std::make_shared;
using std::shared_ptr;
template <typename T>
struct chainNode
{
T element;
shared_ptr<chainNode> next;
chainNode(const T &theElement)
{
element = theElement;
next = nullptr;
}
chainNode(const T &theElement, const shared_ptr<chainNode<T>> theNext)
{
element = theElement;
next = theNext;
}
};
#endif// !CHAINNODE_H
chain.h:
#pragma once
#include"chainNode.h"
#include<memory>
#ifndef CHAIN_H
#define CHAIN_H
using std::shared_ptr;
using std::make_shared;
template<typename T>
class chain//下标从1开始{
public:
chain() {};
chain(const T elementList[], constint leng);
void insert(int pos, const T &theElement);
void erase(const T &theElement);
void output()const;
private:
shared_ptr<chainNode<T>> firstNode;
int chainSize;
};
template<typename T>
chain<T>::chain(const T elementList[],constint leng)//链表长度至少为2{
firstNode = make_shared<chainNode<T>>(elementList[0]);
chainSize = 1;
auto pos(firstNode);
for(int i = 1; i < leng; i++)
{
pos->next = make_shared<chainNode<T>>(elementList[i]);
pos = pos->next;
chainSize++;
}
}
template<typename T>
void chain<T>::insert(int situ, const T &theElement)
{
auto targetNode = make_shared<chainNode<T>>(theElement);
if (situ == 1)
{
targetNode->next = firstNode;
firstNode = targetNode;
chainSize++;
return;
}
situ-=2;
auto fron(firstNode);
while (situ && fron != nullptr)
{
fron = fron->next;
situ--;
}
auto tail(fron->next);
fron->next = targetNode;
targetNode->next = tail;
chainSize++;
return;
}
template<typename T>
void chain<T>::erase(const T &theElement)
{
if (firstNode->element == theElement)
{
firstNode = firstNode->next;
chainSize--;
return;
}
auto fron(firstNode);
auto pos(fron->next);
while (pos!=nullptr)
{
if (pos->element == theElement)
{
fron->next = pos->next;
break;
}
fron = fron->next;
pos = fron->next;
}
chainSize--;
}
template<typename T>
void chain<T>::output()const
{
auto pos(firstNode);
while (pos != nullptr)
{
cout << pos->element << ‘‘;
pos = pos->next;
}
cout << endl;
}
#endif// !CHAIN_H
chain.cpp:
//
chain2.cpp: 定义控制台应用程序的入口点。
//
#include
"
stdafx.h
"
#include<iostream>
#include"chain.h"using std::cout;
using std::endl;
int main()
{
double list[5] = { 2,4,6,8,10 };
chain<double> chainList(list,5);//初始化 chainList.output();
chainList.insert(1, 1);
chainList.insert(3, 3);
chainList.output();
chainList.erase(3);
chainList.output();
chainList.erase(1);
chainList.output();
getchar();
return0;
}
运行结果:
原文:http://www.cnblogs.com/mu-ye/p/7634418.html
内容总结
以上是互联网集市为您收集整理的C++链表,尽量使用C++11全部内容,希望文章能够帮你解决C++链表,尽量使用C++11所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。