数据结构—链表(续)

List.h头文件源代码:

#ifndef _LIST_H_

#define _LIST_H_

 

//链表类的前置声明

template

class List;

 

template

class ListNode    //节点类

{

    friend class List;

    private:

        Type data;    //节点存储数据

        ListNode* link;    //指向下一个节点的指针

        ListNode(Type);        //节点的构造函数

};

 

template

class List    //链表类

{

    public:

        List(){first=0;};    //链表的构造函数

        void Insert(Type);    //插入节点

        void Delete(Type);    //删除节点

        void Invert();    //反转链表

        void Concatenate(List);    //合并链表

        void Show();

        

    private:

    ListNode* first;

};

 

//节点构造函数的实现

template

ListNode::ListNode(Type elemnt)

{

    data=elemnt;

    link=0;

}

 

//链表类插入函数的实现

template

void List::Insert(Type k)

{

    ListNode* newnode=new ListNode(k);

    newnode->link=first;    //原来的头指针后移

    first=newnode;        //插入的新的节点指针成为头指针

    

}

 

template

void List::Delete(Type k)

{

    ListNode* previous=0;    //保存前一个节点

    ListNode* current;    //循环指针

    for(current=first;current&&current->data!=k;previous=current,current=current->link)

    {

        //空循环

    }

    if(current)

    {

        if(previous)    //删除节点不是第一个节点的情况

            previous->link=current->link;

        else    //删除节点为第一个节点的情况

            first=first->link;

            delete current;

    }

 

}

 

//链表类中反转链表

template

void List::Invert()

{

    ListNode* p=first;    //声明两个指针,这个指针指向头节点

    ListNode* q=0;    //这个指针指向尾节点

    while(p)

    {

        ListNode* r=q;

        q=p;

        p=p->link;

        q->link=r;

    }

    first=q;

}

 

//链表类中实现两个链表的连结

template

void List::Concatenate(List b)

{

    if(!first)

    {

        first=b.first;

        return;

    }

    if(b.first)

    {

        ListNode* p;

        for(p=first;p->link;p=p->link);    //空循环,寻找第一个链表的尾节点

        p->link=b.first;

        

    }

}

 

 

template

void List::Show()

{

    for(ListNode*current=first;current;current=current->link)

    {

        std::cout<<current->data;

        if(current->link)

            std::cout<<" -> ";

    }

    std::cout<<std::endl;

}

 

#endif主程序源代码:

#include

#include"List.h"

 

using namespace std;

 

int main()

{

    List intList;

    intList.Insert(5);

    intList.Insert(15);

    intList.Insert(25);

    intList.Insert(35);

    intList.Show();

    intList.Delete(15);

    intList.Show();

    List charList;

    charList.Insert('a');

    charList.Insert('b');

    charList.Insert('c');

    charList.Insert('d');

    charList.Show();

    charList.Invert();

    charList.Show();

    List char2List;

    char2List.Insert('e');

    char2List.Insert('f');

    char2List.Show();

    char2List.Invert();

    char2List.Show();

    charList.Concatenate(char2List);

    charList.Show();

    return 0;

}

运行结果:

 

数据结构—链表(续)

posted @ 2016-04-24 18:06  硫酸亚铜  阅读(155)  评论(0编辑  收藏  举报