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

数组的缺点:当插入数据时,后面的所有数据都要向后移位,删除数据时,后面的数据都要向前移位
所以出现链表,链表的插入和删除都比较快,链表不需要移位。
下面使用友元类和嵌套类实现链表
在VS2013中新建项目,在头文件中添加ThreeLetterList.h在源文件中添加main.cpp

//ThreeLetterList.h
#ifndef THREELETTERLIST_H
#define THREELETTERLIST_H

#include

class ThreeLetterList{
private:
    //嵌套类
    class ThreeLetterNode{
    public:
        char data[3];
        ThreeLetterNode * link;
    };
    ThreeLetterNode * first;
public:
    void test();
    void show();
};

void ThreeLetterList::test(){
    ThreeLetterNode *f = new ThreeLetterNode();
    f->data[0] = 'B';
    f->data[1] = 'A';
    f->data[2] = 'T';
    f->link = 0;
    first = f;

    f = new ThreeLetterNode();
    f->data[0] = 'C';
    f->data[2] = 'T';
    f->data[1] = 'A';
    f->link = 0;
    first->link = f;
}
void ThreeLetterList::show(){
    std::cout << first->data[0] << first->data[1] << first->data[2] << " -> "
        << first->link->data[0] << first->link->data[1] << first->link->data[2] << std::endl;
}

#endif
//main.cpp
#include<iostream>
#include"ThreeLetterList.h"

using namespace std;

class List;

class Node{
friend class List;//使用友元类
private:
    int data;//节点里的数据
    Node* link;//指向下一个节点的指针
};

class List{
public:
    void test();
    void show();
private:
    Node * first;
};

void List::show(){
    cout << first->data << " -> "
        << first->link->data << " -> "
        << first->link->link->data << endl;
}
void List::test(){
    Node *f = new Node();
    f->data = 44;
    f->link = 0;
    first = f;

    f = new Node();
    f->data = 72;
    f->link = 0;

    first->link = f;

    f = new Node();
    f->data = 210;
    f->link = 0;
    first->link->link = f;
}

int main(){
    List a;
    a.test();//创建三个节点
    a.show();

    ThreeLetterList l;
    l.test();
    l.show();
    cout << "OK" << endl;
    system("pause");
    return 0;
}

数据结构与算法(C语言版)__链表_第1张图片

总结:链表是第二常用的数据结构,链表有单链表。但是这里没有写链表的删除,今后会重新实现完整的链表。

你可能感兴趣的:(数据结构与算法-C)