题解 | #牛牛的链表交换#
牛牛的链表交换
https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include <math.h>
#include<stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node* next;
} Node ;
Node* createnode(int num) {
Node* ptr = (Node*)malloc(sizeof(Node));
if (ptr == NULL) {
printf("malloc error!\n");
exit(0);
}
ptr->num = num;
ptr->next = NULL;
return ptr;
}
void add_node(Node* head,int num)
{
Node* q=(Node*)malloc(sizeof(Node));
q->num=num;
q->next=NULL;
Node *p=head;
while(p->next!=NULL)
{
p=p->next;
}
p->next=q;
}
void swap_node(Node* head, int n) {
Node* p = head;
while (n--)
p = p->next;
int num1 = p->num, num2 = p->next->num;
p->num = num2;
p->next->num = num1;
}
void Printlist(Node* head) {
Node* p = head;
while (p) {
printf("%d ", p->num);
p = p->next;
}
}
int main() {
int n;
scanf("%d", &n);
int* a = (int*)malloc(n * sizeof(int));
if (a == NULL) {
printf("malloc error!\n");
exit(0);
}
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
Node* head=createnode(a[0]);
for (int i = 1; i < n; i++)
add_node(head, a[i]);
swap_node(head, 0);
swap_node(head, n - 2);
Printlist(head);
Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
free(a);
return 0;
}
查看12道真题和解析
