#include <iostream>
using namespace std;
//链表节点定义
template <class T>
struct SLNode{
T data;
SLNode<T>* next;
SLNode(SLNode* nextnode = NULL){
next = nextnode;
}
SLNode(const T& item,SLNode* nextnode = NULL){
data = item;
next = nextnode;
}
};
//链表类定义
template<class T>
class SLList{
private:
SLNode<T>* head;
int length;
public:
SLList(){
head = new SLNode<T> ();
}
~SLList();
bool Isempty(){//判断链表是否为空
return head==NULL;
}
int Length(){//返回链表的长度
return length;
}
bool Find(int k,T& item );//将链表第K个节点的值赋給item
int Search(const T& item);//在链表中查找值为item的节点并返回在表中的位置
void Insert(int k,T item);//在第K个节点后插入值为item的节点
void Delete(int k,T& item);//删除链表中第K个节点,并将其值赋給item
void Show();
};
template<class T>
bool SLList<T> :: Find(int k , T& item){
if(k<0){
cout<<"存取位置不合法!"<<endl;
return false;
}
SLNode<T>* p = head;
int i = 0;
while(p!=NULL&& i<k-1){
p=p->next;
++i;
}
if(p==NULL){
cout<<"无此节点!"<<endl;
return false;
}
item = p->data;
return true;
}
template<class T>
int SLList<T> :: Search(const T& item){
SLNode<T>* p = head;
int i = 0;
while(p!=NULL&&p->data!=item){
p = p->next;
++i;
}
if(p==NULL){
cout<<"无此节点!"<<endl;
return -1;
}
return i;
}
template<class T>
void SLList<T> :: Delete(int k,T&item){
SLNode<T>* p = head,*q;
int i = 0;
if(k<0){
cout<<"删除不合法!"<<endl;
return ;
}
while(p!=NULL&&i<k-2){
p = p->next;
++i;
}
if(p->next==NULL){
cout<<"无此节点!"<<endl;
return ;
}
q = p->next;
p->next = q->next;
item = q->data;
--length;
delete q;
}
template<class T>
void SLList<T> :: Insert(int k,T item){
if(k<0){
cout<<"插入位置不合法!"<<endl;
return ;
}
SLNode<T> *p,*q;
int i = 0;
if(k == 0 ){
head->data = item;
head->next = NULL;
length++;
return ;
}
p = head ;
if(k == 1){
SLNode<T>* s = new SLNode<T>(item);
p->next = s;
length++;
return ;
}
while(p!=NULL&&i<k-1){
p = p->next;
++i;
}
if(p == NULL){
cout<<"插入位置不合法!"<<endl;
return ;
}
SLNode<T>* s = new SLNode<T>(item);
q = p->next;
p->next = s;
s->next = q;
++length;
return ;
}
template<class T>
void SLList<T> :: Show(){
SLNode<T>* p;
if(head == NULL){
cout<<"链表为空!"<<endl;
return ;
}
p = head;
while(p!=NULL){
if(p->next == NULL){
cout<<p->data<<endl;
return ;
}
cout<<p->data<<"->";
p = p->next;
}
return ;
}
template<class T>
SLList<T> :: ~SLList(){
SLNode* p = head;
SLNode* q = p;
while(p!=NULL){
p = p->next;
delete q;
}
}
int main() {
SLList<int>* sllist = new SLList<int>();
for(int i = 0;i< 10; i++){
sllist->Insert(i,10-i);
}
sllist->Show();
int a = sllist->Search(2);
cout<<a<<endl;
cout<<sllist->Length()<<endl;
sllist->Find(2,a);
cout<<a<<endl;
sllist->Delete(3,a);
cout<<a<<endl<<sllist->Length()<<endl;
sllist->Show();
return 0;
}
[面试准备】数据结构--链表
最新推荐文章于 2024-06-21 14:39:12 发布