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

牛牛的链表交换

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

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

typedef struct Node{
    int data;
    struct Node* next;
} Node;

int main() {
    int count, value;
    scanf("%d", &count);

    Node* head = (Node*) malloc(sizeof(Node));
    Node* current = head;

    int i = 0;

    for (i = 0; i < count; i++) {
        scanf("%d", &value);
        current->data = value;
        current->next = (Node*) malloc(sizeof(Node));
        current = current->next;
    }

    current = head;

    Node *tmp = (Node*) malloc(sizeof(Node));
    tmp->data = current->data;
    current->data = current->next->data;
    current->next->data = tmp->data;

    current = head;

    for (i = 0; i < count - 2; i++)
    {
        current = current->next;
    }

    tmp->data = current->data;
    current->data = current->next->data;
    current->next->data = tmp->data;

    current = head;

    while (current->next != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    return 0;
}

全部评论

相关推荐

头像
11-09 12:17
清华大学 C++
out11Man:小丑罢了,不用理会
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务