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

牛牛的链表交换

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

#include <stdio.h>
#include <stdlib.h>
typedef struct Like{
    int data;
    struct Like* next;
}Like;

void chuangjian(Like** L,int n){
    Like* r= *L;
    Like*p;
    for(int i=0;i<n;i++){
        p = (Like*)malloc(sizeof(Like));;
        scanf("%d",&p->data);
        p->next = NULL;
        r->next = p;
        r=p;
    }
}



int main() {
   Like* L = (Like*)malloc(sizeof(Like));;
   L->next = NULL;
   int n;
   scanf("%d",&n);
   chuangjian(&L,n);

    //交换
    Like* p1=L->next;
    Like* p2=p1->next;
    int tmp = p1->data;
    p1->data=p1->next->data;
    p2->data = tmp;

    //最后两个
    int xiabiao=0;
    while(p1->next){
        p1=p1->next;
        xiabiao++;
    }
    xiabiao--;//利用next来算;
    p1=L->next;
    for(int i=0;i<xiabiao;i++){
        p1=p1->next;
    }
    p2=p1->next;
     tmp = p1->data;
    p1->data=p1->next->data;
    p2->data = tmp;


    p1=L->next;
    while(p1){
        printf("%d ",p1->data);
        p1=p1->next;
    }

    return 0;
}

全部评论

相关推荐

威猛的小饼干正在背八股:挂到根本不想整理
点赞 评论 收藏
分享
评论
1
1
分享
牛客网
牛客企业服务