AcWing 3709. 单链表节点交换[C]
原题链接
简单
作者:
Losky
,
2024-04-24 09:02:09
,
所有人可见
,
阅读 1
C 代码
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}LNode;
LNode *addNode(LNode *list)
{
LNode *head = NULL;
LNode *tail = NULL;
int n;
scanf("%d", &n);
while(n--)
{
LNode *newNode = (LNode *)malloc(sizeof(LNode));
scanf("%d",&newNode->data);
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 交换相邻两个节点的数据
void swapNodes(LNode *node1, LNode *node2)
{
int temp = node1->data;
node1->data = node2->data;
node2->data = temp;
}
LNode *swapPairs(LNode *head)
{
LNode *dummy = (LNode *)malloc(sizeof(LNode)); // 创建虚拟头节点,简化边界处理
dummy->next = head;
LNode *prev = dummy;
LNode *current = head;
while (current != NULL && current->next != NULL)
{
LNode *nextNext = current->next->next; // 记录当前节点后面第二个节点
// 交换当前节点和其后继节点的数据
swapNodes(current, current->next);
// 移动指针到下一对待交换节点
prev = current;
current = nextNext;
}
// 返回新链表的头节点
return dummy->next;
}
int main()
{
LNode *head = addNode(NULL);
head = swapPairs(head);
LNode *current = head;
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
printf("\n");
return 0;
}