【发布时间】:2020-11-14 08:50:11
【问题描述】:
我有一个单链表,其中我得到了struct Node* head,返回值为void。我想成对交换而不复制数据。
例如,如果输入为2->4->6,则输出为4->2->6。但如果输入为2->4->6->7,则输出为4->2->7->6。
这是我的代码,但它不起作用。
void swapPairs(struct Node *head) {
struct Node *node;
while (head && head->next) {
struct Node *nxt = head->next;
head->next = nxt->next;
nxt->next = head;
node->next = nxt;
node = head;
head = node->next;
}
}
【问题讨论】:
-
swapPairs()的参数必须是struct Node **head或者您必须将返回类型从void更改为struct Node *以便您可以返回新的头节点以分配给原始列表指针调用者。
标签: c linked-list swap singly-linked-list function-definition