# 線性表的鏈表的增刪查改等的操做

線性表的鏈表的增刪查改等的操做

#include<stdio.h>
//d定義類型
typedef int LDateType;
//定義結構體類型
typedef struct listNode
{
    LDateType _date;
    struct listNode* _next;
}listNode;
//定義頭指針
typedef struct list
{
    listNode* _head;
}list;
//初始化頭指針
void InistList(list* lst)
{
    if (lst == NULL)
        return;
    //初始化爲空的鏈表
    lst->_head = NULL;
}
listNode* creatNode(LDateType val)
{
    listNode* node = (listNode*)malloc(sizeof(listNode));
    node->_date = val;
    node->_next = NULL;
    return node;
}
//尾插
void listPushBack(list* lst, LDateType val)
{
    if (lst == NULL)
        return;
    //空鏈表插入
    if (lst->_head==NULL)
    {
        lst->_head = creatNode(val);
    }
    //非空鏈表尾插
    else
    {
        listNode* tail = lst->_head;
        while (tail->_next != NULL)
        {
            tail = tail->_next;
        }
        tail->_next = creatNode(val);
    }

}
//尾刪
void listPopBack(list* lst)
{
    if (lst == NULL||lst->_head==NULL)return;
    struct listNode* tail = lst->_head;
    struct listNode* prev = NULL;
    while (tail->_next != NULL)
    {
        prev = tail->_next;
        tail = tail->_next;
    }
    //刪除節點
    free(tail);
    //修改指向
    if (prev == NULL)//刪除的爲頭結點,更新頭結點
        lst->_head = NULL;
    else
    prev->_next = NULL;
}
//頭插
void listPushFront(list* lst, LDateType val)
{
    if (lst == NULL)return;
    //空的鏈表,插入第一個數據
    if (lst->_head == NULL)
        lst->_head = creatNode(val);
    else
    {
        listNode* node = creatNode(val);
        listNode* next = lst->_head;
        lst->_head = node;
        node->_next = next;
    }
}
//頭刪
void listPopFront(list *lst)
{
    if (lst == NULL || lst->_head == NULL)return; 
    listNode* next = lst->_head->_next;
    //釋放頭結點
    free(lst->_head);
    lst->_head = next;
}
//第一個元素後後插入
void listInsertAfter(listNode* cur, LDateType val)
{
    listNode* node = creatNode(val);
    listNode* next = cur->_next;
    cur->_next = node;
    node->_next = next;
}
//刪除第二個元素
void listEraseAfter(listNode* cur)
{
    listNode* next = cur->_next;
    if (next == NULL)return;
    listNode* nextnext = next->_next;
    free(next);
    cur->_next=nextnext;
}
//查找值爲val,返回地址
listNode* listFind(list* lst,LDateType val)
{
    if (lst == NULL || lst->_head == NULL)return;
    //從第一個值開始遍歷
    listNode* cur = lst->_head;
    while (cur)
    {
        if (cur->_date == val)
            return cur;
        cur = cur->_next;
    }
    return NULL;
}
//求鏈表的大小
int listSize(list* lst)
{
    if (lst == NULL)return;
    int count = 0;
    listNode* next = lst->_head;
    while (next)
    {
        next = next->_next;
        count++;
    }
    return count;
}
//銷燬鏈表
void listDestroy(list* lst)
{
    if (lst == NULL||lst->_head==NULL)return;
    listNode*  ps = lst->_head,*next = NULL;
    while (ps)
    {
        next = ps->_next;
        free(ps);
        ps = next;
    }
    lst->_head = NULL;

}
相關文章
相關標籤/搜索