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

牛牛的链表交换

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

#include <stdio.h>
#include <stdlib.h>
typedef struct List_ {
    int data;
    struct List_* next;
} List, *Listp;
Listp CreatList() { //创建一个节点
    Listp new = (Listp)malloc(sizeof(List));
    new->data = 0;
    new->next = NULL;
    return new;
}
void exchange_first(Listp head) { //交换第一个和第二个节点
    Listp current = head;
    Listp temp = current;
    current = head->next;
    head->next = current->next;
    temp = current->next->next;
    current->next->next = current;
    current->next = temp;

}

void exchange_end(Listp head) { //交换最后一个和倒数第二个节点
    Listp current = head;
    while (current->next != NULL) {
        if ( NULL == current->next->next->next ) {
            Listp temp = NULL;
            temp = current->next;
            current->next = current->next->next;
            current->next->next = temp;
            temp->next = NULL;
            break;
        }
        current = current->next;
    }

}

void print(Listp head) { //打印所有节点
    Listp current = head;
    while (current->next != NULL) {
        printf("%d ", current->next->data );
        current = current->next;
    }
}

int main() {
    Listp head = CreatList();
    Listp current = head;
    int len = 0;
    scanf("%d", &len);
    for (int i = 0; i < len; i++) {//创建列表
        Listp temp = CreatList();
        current->next = temp;
        current = current->next;
    }

    current = head->next;
    for (int i = 0; i < len; i++) {//对列表初始化
        scanf("%d", ¤t->data);
        current = current->next;
    }

    exchange_first(head);
    exchange_end(head);
    print(head);

    return 0;
}

全部评论

相关推荐

阿里巴巴各部门年终奖开奖了,有人拿到了220w
真烦好烦真烦:拿命换钱呢,公司给你220万,肯定是因为你对公司的贡献大于220万,想想要多厉害多累才能达到
投递阿里巴巴集团等公司10个岗位 >
点赞 评论 收藏
分享
04-17 18:32
门头沟学院 Java
野猪不是猪🐗:他跟你一个学校,你要是进来之后待遇比他好,他受得了?
点赞 评论 收藏
分享
03-27 17:33
门头沟学院 Java
代码飞升:同学院本,你要注意hr当天有没有回复过,早上投,还要打招呼要推销自己,不要一个劲投
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务