将一个单向链表插入到一个循环链表尾部

发布于:2024-10-13 ⋅ 阅读:(10) ⋅ 点赞:(0)

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

typedef char datatype;
typedef struct node
{
    datatype data;
    struct node *next;
} NODE_S;

//创建循环链表
NODE_S *createCircleLinkList()
{
    NODE_S *p = (NODE_S *)malloc(sizeof(NODE_S));
    if (NULL == p)
    {
        perror("p malloc err");
        return NULL;
    }
    p->next = p;
    return p;
}

//创建单向链表
NODE_S *createLinkList()
{
    NODE_S *h = (NODE_S *)malloc(sizeof(NODE_S));
    if (NULL == h)
    {
        perror("h malloc err");
        return NULL;
    }
    h->next = NULL;
    return h;
}
//单向链表长度
int lengthLinkList(NODE_S *h)
{
    int i = 0;
    while (h->next != NULL)
    {
        h = h->next;
        i++;
    }
    return i;
}

//循环链表插入数据
int insertIntoCircleLinkList(NODE_S *p,int post,datatype data)
{
    NODE_S *pnew = (NODE_S *)malloc(sizeof(NODE_S));
    if (NULL == pnew)
    {
        perror("pnew malloc err");
        return -1;
    }
    NODE_S *q = p;
    pnew->data = data;
    pnew->next = NULL;
    for (int i = 0; i < post; i++)
    {
        q = q->next;
    }
    pnew->next = p;
    q->next = pnew;
    return 0;
}
//单向链表插入数据
int insertIntoLinkList(NODE_S *h, int post, datatype data)
{
    if (post < 0 || post > lengthLinkList(h))
    {
        printf("insertIntoLinkList err");
        return -1;
    }
    NODE_S *hnew = (NODE_S *)malloc(sizeof(NODE_S));
    if (NULL == hnew)
    {
        perror("pnew malloc err");
        return -1;
    }
    hnew->data = data;
    hnew->next = NULL;
    for (int i = 0; i < post; i++)
    {
        h = h->next;
    }
    hnew->next = h->next;
    h->next = hnew;
    return 0;
}

NODE_S *insertLinklistToCircle(NODE_S *p, NODE_S *h)
{
    NODE_S *t = p;
    NODE_S *r = h;
    while (t->next != NULL)
    {
        t=t->next;
        if (t->next == p)
        {
            r = h->next;
            h->next=NULL;
            t->next = r;
        }
    }
    t->next = p;
    return p;
}

//单向循环链表遍历
void showCircleLinkList(NODE_S *p)
{
    NODE_S *q = p->next;
    do
    {
        printf("%c ",q->data);
        q=q->next;
    } while (q != p);
    printf("\n");
}
int main(int argc, char const *argv[])
{
    NODE_S *p = createCircleLinkList();
    NODE_S *h = createLinkList();
    insertIntoCircleLinkList(p,0,'A');
    insertIntoCircleLinkList(p,1,'B');
    insertIntoCircleLinkList(p,2,'C');
    insertIntoCircleLinkList(p,3,'D');
    insertIntoLinkList(h,0,'E');
    insertIntoLinkList(h,1,'F');
    insertIntoLinkList(h,2,'G');
    insertLinklistToCircle(p,h);
    showCircleLinkList(p);
    return 0;
}

 云尖软件开发笔试题