题解 | 牛牛的链表交换
牛牛的链表交换
https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include <stdio.h>
#include <stdlib.h>
// write your code here......
//定义链表节点结构
typedef struct Node
{
int data;
struct Node* next;
}Node;
void printList(Node* node)
{
Node* current = node;
while(current!=NULL)
{
printf("%d",current->data);
if(current->next!=NULL)
{
printf(" ");
}
current = current->next;
}
printf("\n");
}
int main() {
int n;
scanf("%d",&n);
if(n<2)
{
return 0;
}
int* arr=(int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d",&arr[i]);
}
// write your code here......
//根据数组创建链表
Node* head = NULL;
Node* tail = NULL;
for(int i=0;i<n;i++)
{
Node* newnode = (Node*)malloc(sizeof(Node));
newnode->data=arr[i];
newnode->next=NULL;
if(head==NULL)
{
head = newnode;
tail=newnode;
}else {
tail->next=newnode;
tail=newnode;
}
}
//交换前两个节点
Node* first = head;
Node* second= head->next;
first->next = second->next;
second->next = first;
head = second;//第二个节点成为新节点
//交换最后两个节点
Node* second_last = head;
Node* last = head->next;
Node* before_second_last = NULL;//记录倒数第三个节点
//遍历链表,找到最后两个节点以及它们的前一个节点
while(last!=NULL && last->next !=NULL)
{
before_second_last = second_last;
second_last = last;
last = last->next;
}
//执行交换操作
second_last->next = NULL;
last->next = second_last;
if(before_second_last == NULL)
{
head = last;
}else {
before_second_last->next = last;
}
printList(head);//打印最终的链表
free(arr);
return 0;
}
最重要的还是要画图理解,某某指针前进下一位置是什么,中间变量指针很重要。
查看9道真题和解析