问题解释:
我必须像这样交换相邻的对:
输入:1 -> 2 -> 3 -> 4 -> 5 -> NULL
输出:2 -> 1 -> 4 -> 3 -> 5 -> NULL
此代码给出段错误。另外我想知道这个逻辑对不对?
listnode* swapPairs(listnode* head) {
/* corner cases not included, don't bother */
listnode *prev = head; //points to first node
listnode *curr = prev -> next; //points to second
head = curr; //displacing head to the second element of list
listnode *next; //points to next of second
while(curr != NULL || prev != NULL) {
next = curr -> next;
curr -> next = prev;
prev -> next = next;
prev = next;
curr = prev -> next;
}
return head;
最佳答案
有几个问题,你没有检查head
或head->next
是否为NULL。然后你不检查 curr = prev -> next;
是否为 NULL,如果节点数不是偶数,这是一个问题。
即便如此,该算法还是有缺陷的,第一次交换是正确的,但随后的每次交换都会失败,因为指向第一个节点的节点将被交换,没有更新。
我建议您交换节点的值,这要简单得多,因为不必修改成员 next
。
关于c++ - 交换链表中的相邻节点(迭代方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256660/