C语言链表操作

Python014

C语言链表操作,第1张

typedefstruct_List{intdatastruct_List*next}ListintQuery(List**head,intx){List*p=(*head)->nextintn=1while(p&&p->data!=x){p=p->nextn++}if(p)returnnelsereturn-1}

可以用结构体和指针来实现

定义

定义一个单个元素的结构

typedef struct Chain_tag { // 这里用typedef来定义,方便使用

    int data // 这里的数据可以是任意类型

    //其他数据

    struct Chain_tag *prev, *next// 由于Chain为不完全类型,故只能用指针的方式声明

} Chain

使用:

用单个结构体的指针作为head

#include <malloc.h>

//Chain的定义写在这里

Chain *

alloc_single_chain(int data /*, (其他参数)*/)

{

    Chain *tmp

    

    tmp = malloc(sizeof(Chain))

    tmp.data = data

    //...其余数据初始化

    tmp.prev = tmp.next = NULL // 将前后指针置为NULL

    

    return tmp

}

void

dispose_chain(Chain *target) //其实这里功能简单,用宏实现也可以

{

    free(target)

    return

}

int main()

{

    Chain *head

    Chain *pos

    

    head = alloc_single_chain(10)//初始化起始结点

    head->next = alloc_single_chain(11)//同理。。下一个结点

    

    for (pos = head pos pos = pos->next)//清理垃圾好习惯

    {

       dispose_chain(pos)

    }

    

    return 0

}

这里有几点要注意:

由于链表用指针来实现,故不要忘记分配内存

垃圾清理时一定要从起始结点开始依次向后释放,以防内存泄漏