题解 | #牛牛的链表交换#
牛牛的链表交换
https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include<stdio.h>
#include<stdlib.h>
//定义结构体
typedef struct changenode {
int num;
struct changenode* next;
} node;
int main() {
int n = 0;
scanf("%d", &n);
//创建头节点
node* head = (node*)malloc(sizeof(node));
head->next = NULL;
node* p = head;
//创建新节点
for (int i = 0; i < n; i++) {
node* newnode = (node*)malloc(sizeof(node));
scanf("%d", &newnode->num);
newnode->next = NULL;
//指向最末端的节点
while (p->next != NULL)
p = p->next;
//末端节点与新节点链接
p->next = newnode;
p = p->next;
}
int k = 0;
//遍历链表
node* pt = head->next;
while (pt) {
//节点交换
if (k == 0 || k == n - 2) {
int k = pt->num;
pt->num = pt->next->num;
pt->next->num = k;
}
printf("%d ", pt->num);
//推进
pt = pt->next;
k++;
}
return 0;
}


