[C++]线性链表之单链表

本文详细介绍了单链表的基本概念及其实现方法,包括单链表的创建、插入、删除等核心操作,并提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[文档整理系列] 线性链表之单链表

/*
问题描述:线性表____链表_____单链表 
@date 2017-3-7 
*/ 

#include<iostream>
using namespace std;

template<typename T>
struct node{
	T data;
	node<T> *next;
};

template<typename T>
class LinkedList{
    public:
    	LinkedList();    
		LinkedList(T arr[],int n);  
		~LinkedList();   
		int getLength();  
		void InsertAt(int n,T data);  
		T DeleteAt(int i);     

		T   GetData(int i);      
		int getDataAt(T data);   
		void Print(); 
	private:
	    int length;
		node<T> *first;   
};

template <class T>  
LinkedList<T>::LinkedList(){
    first = new node<T>;
	first->next = NULL;    
	length = 0;	
} 

template <class T>  
LinkedList<T>::LinkedList(T arr[],int n){
    first = new node<T>();   //初始化指针变量  
    first->next = NULL;     
    
    for(int i = 0;i<n;i++){
    	node<T> s;
    	s.data = arr[i];
    	s.next = first->next;
    	first->next = &s;
	}
	
    length = n;
	cout<<"初始化成功!"<<endl;  //test
}

 
template<typename T>
LinkedList<T>::~LinkedList(){   

   node<T> *q;
   while (first)                         //释放单链表的每一个结点的存储空间
   {
     q=first;                            //暂存被释放结点
     first=first->next;                  //工作指针p指向被释放结点的下一个结点,使单链表不断开
     delete q;    
}
   cout<<"析构(销毁)成功!"<<endl;	 //test
}

template<typename T>
int LinkedList<T>::getLength(){
	return length;
}

template< typename T> 
void LinkedList<T>::InsertAt(int n,T data){
    
	cout<<"成功插入第"<<n<<"个位置!"<<endl;
}
  
int main(){
    int arr[6]={7,19,4,5,6,9};
    LinkedList<int> t(arr,6);  
//    t.InsertAt(7,689); 
	return 0;
}

  

转载于:https://www.cnblogs.com/johnnyzen/p/9277436.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值