日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++之单链表

發布時間:2024/9/21 c/c++ 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++之单链表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、學習要點:
1.模板函數、模板類的應用;
2.尾節點的指針內容為空,有利于計算鏈表長度,和插入和刪除節點是否越界;
3.加深對成員變量應用的認識.
二、程序運行代碼:

#include<stdlib.h> #include<iostream> using namespace std; template<class DataType> struct Node{DataType data;struct Node<DataType> *next; }; template<class DataType> class LinkList{ public:LinkList();LinkList(DataType array[],int n);LinkList(int n,DataType array[]);~LinkList();int GetLength();int GetLocal(DataType x);DataType GetElement(int index);void Insert(int index,DataType x);DataType Delete(int index);void PrintLinkedList(); private:Node<DataType>*first; }; template<class DataType> LinkList<DataType>::LinkList(){first=new Node<DataType>;first->next=NULL; } template<class DataType> LinkList<DataType>::LinkList(DataType array[],int n){first=new Node<DataType>;Node<DataType> *p=first;for(int i=0;i<n;i++){Node<DataType> *temp=new Node<DataType>;temp->data=array[i];temp->next=p->next;p->next=temp;p=p->next;}p->next=NULL; } template<class DataType> LinkList<DataType>::LinkList(int n,DataType array[]){Node<DataType> temp=new Node<DataType>;for(int i=0;i<n;i++){temp->data=array[i];temp->next=first->next;first->next=temp;} } template<class DataType> LinkList<DataType>::~LinkList(){Node<DataType> *p;p=first->next;while(p!=NULL){Node<DataType> *temp;temp=p;p=p->next;delete temp;} } template<class DataType> void LinkList<DataType>::Insert(int index,DataType x){Node<DataType> *p=first->next;int count=0;while(p!=NULL&&count<index-1){p=p->next;count++;}if(p==NULL){throw"插入有誤";}else{Node<DataType> *temp=new Node<DataType>;temp->data=x;temp->next=p->next;p->next=temp;} } template<class DataType> int LinkList<DataType>::GetLocal(DataType x){Node<DataType> *p=first->next;int count=1;while(p!=NULL){if(p->data=x){return count;}p=p->next;count++;}return 0; } template<class DataType> DataType LinkList<DataType>::GetElement(int index){Node<DataType> *p=first->next;int count=1;while(p!=NULL&&count<index){p=p->next;count++;}if(p==NULL){throw"error position"}else{return p->data;} } template<class DataType> int LinkList<DataType>::GetLength(){Node<DataType> *p=first->next;int count=0;while(p!=NULL){count++;p=p->next;}return count; } template<class DataType> void LinkList<DataType>::PrintLinkedList(){Node<DataType> *p;p=first->next;while(p!=NULL){cout<<p->data<<" ";p=p->next;} } int main(){int array[]={1,3,5,2,7,6,9,8,10,4};LinkList<int> LinkedList=LinkList<int>(array,10);LinkedList.PrintLinkedList();system("pause");return 0; }

三、程序運行結果:

總結

以上是生活随笔為你收集整理的C++之单链表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。