题解 | #牛牛的链表交换#
牛牛的链表交换
https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; }node; //创建头节点 node *add_head() { node *Head = malloc(sizeof(node)); if (Head == NULL) { printf("out of memory"); exit(1); } Head->next = Head; return Head; } void add_node(node *Head, int data) { node *new = malloc(sizeof(node)); if (new == NULL) { exit(1); } new->data = data; new->next = NULL; node *pT = NULL; pT = Head; if(pT->next != Head) pT = pT->next; new->next = pT->next; pT->next = new; } //节点交换 void swap_node(node *Head) { node *p1 = Head->next; node *p2 = Head->next->next; //前两个节点交换 p1->next = p2->next; p2->next = p1; Head->next = p2; node *pT = NULL; node *pT1 = NULL; node *pT2 = NULL; for (pT = Head; pT->next->next->next != Head; pT = pT->next); for (pT1 = Head; pT1->next->next != Head; pT1 = pT1->next); for (pT2 = Head; pT2->next != Head; pT2 = pT2->next); //后两个节点交换 pT1->next = Head; pT2->next = pT1; pT->next = pT2; } //输出链表 void output(node *Head) { if (Head->next == Head) { return; } node *pT = Head->next; while (pT != Head) { printf("%d ", pT->data); pT = pT->next; } } int main() { node *Head = add_head();//返回头节点的地址给头指针 int n; scanf("%d",&n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d",&arr[i]); } //将数据插入链表 for (int j = 0; j < n; j++) { add_node(Head, arr[j]); } swap_node(Head); output(Head); return 0; }