首页 > 编程语言 > 详细

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

时间:2015-07-12 12:40:20      阅读:312      评论:0      收藏:0      [点我收藏+]
/*  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:

xiaoq@xq-ubun:~/C/DataStructure$ g++ LList.cpp -o LList.o
xiaoq@xq-ubun:~/C/DataStructure$ ./LList.o 

******************Begin Test**********************

******************Empty List**********************


******************After Append********************
1    2    3    4    




*****************After Insert*******************
1    2    10    3    30    4    
xiaoq@xq-ubun:~/C/DataStructure$ 

 

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

欢迎交流!

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

原文:http://www.cnblogs.com/ruchicyan/p/4640665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!