右向插入的单链表

发布于:2025-04-22 ⋅ 阅读:(17) ⋅ 点赞:(0)

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

typedef uint32_t ElemTyp;

typedef struct st_single_chain_list {
    ElemTyp dat;
    struct st_single_chain_list *next;
} tagLink_t;

ElemTyp total;

tagLink_t *init_single_chain_list(ElemTyp value)
{
    tagLink_t *tmp = (tagLink_t *)malloc(sizeof(tagLink_t));
    if (tmp == NULL) {
        printf("original node create fail!\n");
        return NULL;
    }
    tmp->dat = value;
    tmp->next = NULL;
    total = 1;     // 头节点
    return tmp;
}

void insert_an_element(tagLink_t *p, ElemTyp value, ElemTyp posi)
{
    tagLink_t *head = NULL;
    tagLink_t *tmp = NULL;
    tagLink_t *q = p;
    tagLink_t *prev = NULL;
    ElemTyp append_flag = 0;
    ElemTyp i = 0;
    if (posi == 0) {
        printf("insert before head node!\r\n");
        return;
    }
    if (posi > total) {
        printf("insert position: %d invalid! total :%d\r\n", posi, total);
        return;
    } else if (posi == total) {
        append_flag = 1;
    } else {
        append_flag = 2;
    }
    tmp = (tagLink_t *)malloc(sizeof(tagLink_t));
    if (tmp == NULL) {
        printf("%d node create fail!\r\n", posi);
        return;
    }
    q = p;
    if (append_flag == 1) {
        while (q != NULL) {
            prev = q;
            q = q->next;
        }
        q = prev;
        tmp->dat = value;
        tmp->next = NULL;
        q->next = tmp;
        total++;
    } else {
        for (i = 0; i < posi - 1; i++) {
            q = q->next;
        }
        tmp->dat = value;
        tmp->next = q->next;
        q->next = tmp;
        total++;
    }
}

int main()
{
    tagLink_t *Link = NULL;
    tagLink_t *p = NULL;
    ElemTyp index = 0;
    Link = init_single_chain_list(36);
    insert_an_element(Link, 3, 0);
    insert_an_element(Link, 4, 1);
    insert_an_element(Link, 5, 2);
    insert_an_element(Link, 6, 3);
    insert_an_element(Link, 7, 4);
    insert_an_element(Link, 8, 5);
    insert_an_element(Link, 9, 6);
    insert_an_element(Link, 10, 7);
    insert_an_element(Link, 11, 8);
    insert_an_element(Link, 12, 9);
    insert_an_element(Link, 100, 6);
    insert_an_element(Link, 55, 5);

    for (p = Link; p != NULL; p = p->next) {
        printf("%d----%d\n", index++, p->dat);
    }

    return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到