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

牛牛的链表交换

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;
}

全部评论

相关推荐

03-18 09:45
莆田学院 golang
牛客749342647号:佬,你这个简历模板是哪个,好好看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务