数据结构小结——链表

来源:互联网 发布:本地搜索引擎seo 编辑:程序博客网 时间:2024/06/09 19:01

前面几篇讲了顺序表,是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中,重点是内存地址是连续的。而链表也是顺序表的一种,只不过存储空间在内存是不连续的,最终由指针将所有的节点连接起来构成一个顺序表

链表其实也很简单,只是多了一个连接下一个节点的指针,我们来看看它的结构:

typedef int LinkData;typedef struct _node{    LinkData data;    struct _node *next;}Node;

这里的next就是指向下一个节点的指针,存储下一个节点的地址。

怎么来用呢,第一步肯定是要创建这个链表了,即给它分配空间:

int Create_List(){    Node *node = (Node *)malloc(sizeof(Node)/sizeof(char));    if(node == NULL)    {        free(node);        return FALSE;    }    return TRUE;}

尾插法不难,这里就不给出来了,有点复杂的是在中间插入一个节点:

int Insert_Pos(Node *h, int pos, LinkData data){    if (h == NULL || pos < 1)        return FALSE;    // 找要插入位置的前一个结点    Node *tmp = h;    int i;    for (i = 0; i < pos-1; i++)    {        if (tmp == NULL)            break;        tmp = tmp->next;    }    if (tmp == NULL)   // 越界    {        printf("插入位置越界\n");        return FALSE;    }    Node *node = (Node*)malloc(sizeof(Node)/sizeof(char));    if (node == NULL)    {        return FALSE;    }    node->data = data;    node->next = tmp->next;    tmp->next  = node;    return TRUE;}

有插入当然就要有删除了。

int Delete_Pos(Node* h, int pos){    if (h == NULL || pos < 1)        return FALSE;    // 找要插入位置的前一个结点    Node *tmp = h;    int i;    for (i = 0; i < pos-1; i++)    {        if (tmp->next == NULL)            break;        tmp = tmp->next;    }    if (tmp->next == NULL)   // 越界    {        printf("删除位置越界\n");        return FALSE;    }    Node *p = tmp->next;    tmp->next = p->next;    free(p);    return TRUE;}

代码就贴这么多了,就给几个片段,需要完整代码请直接下载(免积分)

原创粉丝点击