在单链表中插入结点

lixiangrong
2024-01-29 / 0 评论 / 15 阅读 / 正在检测是否收录...

在带头结点单链表值为y的结点前插入一个值为x的结点

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

typedef int dataType;

// 带头结点的单链表
typedef struct linkNode
{
    dataType data;
    struct linkNode *next;
}node,*linkList;

// 1.初始化带头结点的单链表
void init(linkList *head)
{
    node *p = (node*)malloc(sizeof(node));
    p->next = NULL;
    *head = p;
}

// 2.输出链表
void display(linkList head)
{
    node *p = head->next;
    if(!p)
    {
        printf("单链表为空!\n");
        return;
    }
    while (p)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
}

// 3.在链表尾部插入元素
void rearInsert(linkList *head, dataType x)
{
    node *p = *head,*q; // head初值为头结点
    q = (node*) malloc(sizeof(node));
    q->data = x;
    q->next = NULL;
    while (p->next) // 找到尾结点
        p = p->next;
    p->next = q;
}

// 寻找结点值为x的前驱结点
node *findXPre(linkList head, dataType x)
{
    node *p = head->next,*pre = head;
    while (p && p->data != x)
    {
        pre = p;
        p = p->next;
    }
    if(!p)
        return NULL;
    return pre;
}

// 3.8.4.在带头结点单链表值为y的结点前插入一个值为x的结点
void insert(linkList *head, dataType y, dataType x)
{
    node *p = findXPre(*head,y),*q;
    if(!p)
    {
        printf("没有找到这样的结点,无法插入!\n");
        return;
    }
    q = (node*) malloc(sizeof(node));
    q->data = x;
    q->next = p->next;
    p->next = q;
}

int main()
{
    linkList list; // 声明头指针
    init(&list); // 初始化单链表
    for (int i = 1; i <= 10; i++)
        rearInsert(&list,i); // 插入结点
    display(list);
    dataType y = 1,x = 0;
    printf("在带头结点单链表值为%d的结点前插入一个值为%d的结点\n",y,x);
    insert(&list,y,x);
    display(list);
    return 0;
}
0

评论 (0)

取消