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

牛牛的链表交换

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

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

//链表结点定义
struct Node {
    int data;
    struct Node* next;
};

//创建头结点
struct Node* createhead() {
    struct Node* head;
    head = (struct Node*)malloc(sizeof(struct Node));
    head->data = 0;
    head->next = NULL;
    return head;
}

//创建结点
struct Node* createnode(int num) {
    struct Node* newnode;
    newnode = (struct Node*)malloc(sizeof(struct Node));
    newnode->data = num;
    newnode->next = NULL;
    return newnode;
}


int main() {
    int n, num;
    scanf("%d\n", &n);

    struct Node *L = createhead();
    struct Node *p, *q = L;

    //数组转换成链表
    while (scanf("%d ", &num) != EOF) { 
        p = createnode(num);
        //尾插法
        q->next = p;
        q = p;
    }

    //链表前两个结点交换位置
    p = L->next;
    q = L->next->next;
    p->next = q->next;
    q->next = p;
    L->next = q;
    

    //链表最后两个结点交换位置
    p = L->next;
    q = L->next->next;
    while (q->next->next != NULL) {
        p = p->next;
        q = q->next;
    }
    p->next = q->next;
    p->next->next = q;
    q->next = NULL;

    //输出链表的值
    p = L->next;
    while (p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }

    return 0;
}

全部评论

相关推荐

06-20 15:23
门头沟学院 Java
难道你们背八股都不觉得累?现在每天背八股背的我想吐
想去大厂的土豆子:累不累都是对比出来的,八股可比高考、考研轻松多了
点赞 评论 收藏
分享
05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务