题解 | #牛牛的链表交换#

牛牛的链表交换

https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc

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

typedef int data_t;

//定义节点
typedef struct node 
{
    data_t data;
    struct node *next;
}listnode,*listlink;

//表头创建
listlink list_create()
{
    listlink H = (listlink)malloc(sizeof(listnode));
    if(H ==NULL)
    {
        printf("malloc is failed");
        return NULL;
    }
    H->data = 0;
    H->next = NULL;
    return H;
}

//赋值
void list_insert(listlink H)
{
    int value ;
    scanf("%d",&value);
    listlink L = (listlink)malloc(sizeof(listnode));
    if(L ==NULL)
    {
        printf("malloc is failed");
        return ;
    }

    listlink h = H;
    L->data = value;
    L->next = NULL;
    while(h->next !=NULL)
    {
        h = h->next;
    }
    h->next = L;
}

//打印链表
int list_show(listlink H)
{
    listlink h = H->next;
    while(h->next != NULL)
    {
        printf("%d ",h->data);
        h = h->next;
    }
    printf("%d ",h->data);
    return 0;
}

//链表置换
void list_change(listlink H)
{
    listlink h,front1,front2,rear1,rear2;
    front1 = H->next;
    front2 = H->next->next;  
//前两个节点置换
    front1->next = front2->next;
    front2->next = front1;
    H->next = front2;
//后两个节点置换
    for(h = H;h->next->next->next !=NULL;h = h->next);
    for(rear1 = H;rear1->next->next != NULL;rear1 = rear1->next);
    for(rear2 = H;rear2->next != NULL;rear2 = rear2->next);
    h->next = rear2;
    rear2->next = rear1;
    rear1->next = NULL;
}
int main() {
    int n,i;
    listlink H = list_create();
    scanf("%d",&n);
    for(i = 0;i<n;i++)
        list_insert(H);
    list_change(H);
    list_show(H);
    
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务