题解 | #牛牛的链表交换#
牛牛的链表交换
https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include <stdio.h> #include <stdlib.h> //声明结构体 typedef struct List { int date; struct List* next; }List; //新节点 List* BuyNewCode(int x) { List* new=(List*)malloc(sizeof(List)); new->date=x; new->next=NULL; return new; } //尾插 void PushBack(List** pplist,int x) { List* newcode=BuyNewCode(x); if(*pplist==NULL) { *pplist=newcode; } else { //注意细节 List* tail=*pplist; while(tail->next!=NULL) { tail=tail->next; } tail->next=newcode; } } //交换位置 void ChangePosition(List** pplist) { //交换前两个节点 List* cur=*pplist; int temp=cur->date; cur->date=cur->next->date; cur->next->date=temp; //交换后2个节点 List* tail1=*pplist; List* tail2=(*pplist)->next; while(tail2->next!=NULL) { tail1=tail1->next; tail2=tail2->next; } temp=tail1->date; tail1->date=tail2->date; tail2->date=temp; } //打印输出 void Print(List* plist) { List* cur=plist; while(cur!=NULL) { printf("%d ",cur->date); cur=cur->next; } } int main() { List* plist=(List*)malloc(sizeof(List)); plist=NULL; int n=0; scanf("%d",&n); int i=0; int k=0; for(i=0;i<n;i++) { scanf("%d",&k); PushBack(&plist,k); } ChangePosition(&plist); Print(plist); return 0; }