数据结构与算法 :C 单链表头插法/尾插法/删除指定值结点

先上代码

结构体

#include 
#include 

typedef struct nodeList {
    int data; //数据域
    struct nodeList *next; //指针域
} nodeList;

遍历链表


//遍历链表
void TraverseList(struct nodeList *head)
{
    while(head != NULL){
        printf("%d \n",head->data);
        head=head->next;
    }
}

头插法

void HeadCreatList(struct nodeList *head, int n)
{
    struct nodeList *node;
    for (int i = 0; i < n; ++i)
    {
        node=(struct nodeList *)malloc(sizeof(struct nodeList));
        node->data = i;
        node->next = head->next;
        head->next = node;
    }
    head->data = n;
}

头插法,新结点始终在头结点之后,核心在于:

node->data = i;
node->next = head->next;
head->next = node;

尾插法

void TailCreatList(struct nodeList *head, int n)
{
    struct nodeList *node,*end;
    end = head;
    for (int i = 0; i < n; ++i)
    {
        node=(struct nodeList *)malloc(sizeof(struct nodeList));
        node->data = i;
        end->next  = node;
        end           = node;
    }
    head->data = n;
}

尾插法,新结点始终在尾结点之后,核心在于:

node->data = i;
end->next  = node;
end        = node;

删除某个值


void deleteFromList(struct nodeList *head, int target)
{
    struct nodeList *pre,*tmp;
    int count=0;
    tmp = head;
    pre = head;
    head= head->next;

    while(head != NULL){
        if (head->data == target){
            pre->next = head->next;
            free(head);
            count--;
        }else{
            pre = head;                
            count++;
        }
        head= head->next;
    }
    tmp->data = count;
    head = tmp;
}

实测:


int main()
{
    struct nodeList *head,*node;
    
    head=(struct nodeList *)malloc(sizeof(struct nodeList));
    //头结点
    //head->data = NULL;
    head->next = NULL;
    //头插法
    HeadCreatList(head, 5);
    printf("头插法: \n");
    TraverseList(head);
    //尾插法
    head->next = NULL;
    TailCreatList(head, 5);
    printf("尾插法: \n");
    TraverseList(head);
    //删除
    deleteFromList(head,2);
    printf("删除2: \n");
    TraverseList(head);
    free(head);
    head = NULL;
    return 0;
}

执行结果:
数据结构与算法 :C 单链表头插法/尾插法/删除指定值结点_第1张图片

你可能感兴趣的:(链表,c)