/* LList.cpp * Author: Qiang Xiao * Time: 2015-07-12 */ #include<iostream> using namespace std; class Node{ public: int data; Node* ptr; Node(int elem= 0, 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(4); this->head= new Node(); this->tail= new Node(); this->head= init; this->tail= init; this->length= 0; } LList::~LList(){ delete head; delete tail; } bool LList::insert(int pos, Node* node){ int i= 0; 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(1); Node* node2= new Node(2); Node* node3= new Node(3); Node* node4= new Node(4); 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(10); int pos= 2; list->insert(pos,node5); Node* node6= new Node(30); pos= 4; list->insert(pos,node6); cout<<"\n\n*****************After Insert*******************\n"; list->print(); return 0; }
Console display:
[email protected]:~/C/DataStructure$ g++ LList.cpp -o LList.o [email protected]-ubun:~/C/DataStructure$ ./LList.o ******************Begin Test********************** ******************Empty List********************** ******************After Append******************** 1 2 3 4 *****************After Insert******************* 1 2 10 3 30 4 [email protected]-ubun:~/C/DataStructure$
写这个程序主要是练习一下链表的用法。代码中有许多需要改进的地方,敬请指正。
欢迎交流!
时间: 2024-10-13 05:51:38