生活随笔
收集整理的這篇文章主要介紹了
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++之单链表的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。