一个简单链表的C++实现

时间:2023-03-09 23:08:14
一个简单链表的C++实现
/*  LList.cpp
* Author: Qiang Xiao
* Time: 2015-07-12
*/ #include<iostream>
using namespace std; class Node{
public:
int data;
Node* ptr;
Node(int elem= , Node* node= NULL){this->data= elem; this->ptr= NULL;}
}; class LList{
private:
Node* head;
Node* tail;
int length;
public:
LList();
~LList();
bool append(Node*);
bool insert(int, Node*);
void print();
int getLength(){return this->length;}
}; LList::LList(){
Node* init= new Node();
this->head= new Node();
this->tail= new Node();
this->head= init;
this->tail= init;
this->length= ;
} LList::~LList(){
delete head;
delete tail;
} bool LList::insert(int pos, Node* node){
int i= ;
Node* fence= new Node();
fence= this->head;
while(i< pos){
fence= fence->ptr;
i++;
}
node->ptr= fence->ptr;
fence->ptr= node;
this->length++;
return true;
} bool LList::append(Node* node){
this->tail->ptr= node;
this->tail= node;
this->length++;
return true;
} void LList::print(){
Node* p= this->head->ptr;
while(p){
cout<<p->data<<"\t";
p= p->ptr;
}
cout<<endl;
delete p;
} int main(){
cout<<"\n******************Begin Test**********************\n";
Node* node1= new Node();
Node* node2= new Node();
Node* node3= new Node();
Node* node4= new Node();
LList* list= new LList();
cout<<"\n******************Empty List**********************\n";
list->print();
list->append(node1);
list->append(node2);
list->append(node3);
list->append(node4);
cout<<"\n******************After Append********************\n";
list->print();
cout<<"\n\n";
Node* node5= new Node();
int pos= ;
list->insert(pos,node5);
Node* node6= new Node();
pos= ;
list->insert(pos,node6); cout<<"\n\n*****************After Insert*******************\n";
list->print();
return ;
}

Console display:

xiaoq@xq-ubun:~/C/DataStructure$ g++ LList.cpp -o LList.o
xiaoq@xq-ubun:~/C/DataStructure$ ./LList.o ******************Begin Test********************** ******************Empty List********************** ******************After Append******************** *****************After Insert******************* xiaoq@xq-ubun:~/C/DataStructure$

写这个程序主要是练习一下链表的用法。代码中有许多需要改进的地方,敬请指正。

欢迎交流!