题解 | #牛牛的链表交换#
牛牛的链表交换
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;
}
