题解 | #牛牛的链表交换#
牛牛的链表交换
https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include <stdio.h>
#include <stdlib.h>
typedef struct List_ {
int data;
struct List_* next;
} List, *Listp;
Listp CreatList() { //创建一个节点
Listp new = (Listp)malloc(sizeof(List));
new->data = 0;
new->next = NULL;
return new;
}
void exchange_first(Listp head) { //交换第一个和第二个节点
Listp current = head;
Listp temp = current;
current = head->next;
head->next = current->next;
temp = current->next->next;
current->next->next = current;
current->next = temp;
}
void exchange_end(Listp head) { //交换最后一个和倒数第二个节点
Listp current = head;
while (current->next != NULL) {
if ( NULL == current->next->next->next ) {
Listp temp = NULL;
temp = current->next;
current->next = current->next->next;
current->next->next = temp;
temp->next = NULL;
break;
}
current = current->next;
}
}
void print(Listp head) { //打印所有节点
Listp current = head;
while (current->next != NULL) {
printf("%d ", current->next->data );
current = current->next;
}
}
int main() {
Listp head = CreatList();
Listp current = head;
int len = 0;
scanf("%d", &len);
for (int i = 0; i < len; i++) {//创建列表
Listp temp = CreatList();
current->next = temp;
current = current->next;
}
current = head->next;
for (int i = 0; i < len; i++) {//对列表初始化
scanf("%d", ¤t->data);
current = current->next;
}
exchange_first(head);
exchange_end(head);
print(head);
return 0;
}
