c&c++ 链表实现

1. C语言 demo 实现

//  c语言   链表

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct  list_node
{
    int data ;
    struct list_node *next ;
};

typedef struct list_node list_single ;   //定义 结构体别名为 list_single

list_single* deleteList(list_single* l,int num)   //删除
{
    int f = 1;
    list_single *p,*y;
    p = l;
    y = l;
    do
    {
        if(l->data == num)
        {
            f=0;
            p->next = l->next;
        }
        else
        {
            p = l;
            l = l->next;
        }
    }
    while(f);
    return y;
}

void insert(list_single* l,int num)    //插入
{
    list_single *p,*y;
    int i;
    p = l;
    for(i = 0;i<num-1;i++)
    {
        l = l->next;
        if(i != 0)
            p = p->next;
        y = (list_single *)malloc(sizeof(list_single));
        y->data = 9999;
        p->next = y;
        y->next = l;
    }
}

list_single* create(int num)     //创建
{
    list_single *head,*pre,*back;           //1、首先,当然是定义一个头指针
    int i;
    head = (list_single *)malloc(sizeof(list_single));
    head->data = 0;
    head->next = NULL;
    back = head;

    for(i =0; i < num; i++)
    {
        pre = (list_single *)malloc(sizeof(list_single));     //动态分配以结构体大小的空间,并强转成结构体类型指针
        pre->data = i+1;
        back->next = pre;
        pre->next = NULL;
        back = pre;
    }
    return head;
}

int main(void)
{
    int i = 5,j = 0;
    list_single *a,*c,*b,*d;
    a = create(i);
    c = a;
    for(j=0; j<=i; j++)
    {
        printf("%d\n",a->data);
        a = a->next;
    }
    b = deleteList(c,1);
    d = b;
    printf("---------------\n");
    for(j=0; j<i; j++)
    {
        printf("%d\n",b->data);
        b = b->next;
    }
    printf("---------------\n");
    insert(d,2);
    for(j=0; j<=i; j++)
    {
        printf("%d\n",d->data);
        d = d->next;
    }
    return 0 ;
}

2. c++链表 demo 实现

//  c++  链表类
#include <iostream>

using namespace std;

struct data
{
    int num;
    data *next;
};

typedef data list_data;   // 别名:list_data

class list
{
    list_data *head;
public:
    list()
    {
        head = NULL;
    }
    void insertList(int a,int n)    //  插入到 数据 a 后面,
    {
        list_data *p,*y;
        p =(list_data*) new (list_data);
        p->num = n;
        p->next = NULL;
        list_data *h;
        h = head;
        if(head == NULL)  
            head = p;
        else
        {
            while(h->num != a)
            {
                h = h->next;
            }
            y = h->next;
            h->next = p;
            p->next = y;
        }
    }
    void getHeadNum()
    {
        list_data* current=head;
        int i =3;
        while(i--)
        {
            cout<<current->num<<" ";
            current=current->next;
        }
        cout<<endl;
    }


};

int main()
{
    list d;
    d.insertList(0,1);
    d.insertList(1,2);
    d.insertList(2,3);
    d.getHeadNum();
    return 0;
}

阅读更多
文章标签: c
个人分类: 算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭