数据结构与算法(C语言版)__链表2

来源:互联网 发布:自学电子琴的软件 编辑:程序博客网 时间:2024/04/27 16:39

今天用C++里面的模板实现链表
ListNode
List
链表操作:
Insert
Delete
Invert
Concatenate

在VS2013中新建项目,在头文件中加入MyList.h,在源文件中加入main.cpp

//MyList.h#ifndef MYLIST_H#define MYLIST_H#include<iostream>template<class Type> class List;template<class Type>class ListNode{    friend class List<Type>;private:    Type data;    ListNode *link;    ListNode(Type);//构造函数};template<class Type>class List{public:    List(){ first = 0; };    void Delete(Type);    void Insert(Type);    void Invert();    void Concatenate(List<Type>);    void Show();//测试使用的函数private:    ListNode<Type>*first;};//插入是往最前面插入template<class Type>void List<Type>::Insert(Type k){    ListNode<Type> *newnode = new ListNode<Type>(k);//k是存放节点里面的数据;    newnode->link = first;    first = newnode;}template<class Type>ListNode<Type>::ListNode(Type element){    data = element;    link = 0;}template<class Type>void List<Type>::Show(){    for (ListNode <Type> *current = first; current; current = current->link){        std::cout << current->data;        if (current->link)cout << " -> ";    }    std::cout << std::endl;}template<class Type>void List<Type>::Invert(){    ListNode<Type> *p = first, *q = 0;    while (p){        ListNode<Type> *r = q; q = p;        p = p->link;        q->link = r;    }    first = q;}template<class Type>void List<Type>::Delete(Type k){    ListNode<Type> *previous = 0;//前一个    ListNode<Type> *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<class Type>void List<Type>::Concatenate(List<Type>b){    if (!first){ first = b.first; return; }    if (b.first){        ListNode<Type>*p;        for (p = first; p->link; p = p->link);//空循环        p->link = b.first;    }}#endif
//main.cpp#include<iostream>#include "MyList.h"using namespace std;int main(){    cout << "测试:" << endl;    List<int> initList;    initList.Insert(5);    initList.Insert(15);    initList.Insert(25);    initList.Insert(35);    initList.Show();    initList.Delete(15);    initList.Show();    initList.Delete(20);    initList.Show();    initList.Invert();    initList.Show();    List<char> charList;    charList.Insert('a');    charList.Insert('b');    charList.Insert('c');    charList.Insert('d');    charList.Show();    charList.Invert();    charList.Show();    List<char> char2List;    char2List.Insert('e');    char2List.Insert('f');    char2List.Show();    char2List.Invert();    char2List.Show();    charList.Concatenate(char2List);    charList.Show();    system("pause");    return 0;}

总结:链表的开发就是按照这样来开发,我们可以自己动手给链表添加一些功能。以后再开发过程中也是按照这样的流程来开发。

0 0
原创粉丝点击