您的位置:首页 > 其它

利用双重指针来实现单向链表的节点交换

2018-04-02 08:53 246 查看
一道Leetcode中的题:

Given a linked list, swap every two adjacent nodes and return its head.

For example,

Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

以下是摘自讨论区的一个利用双重指针的解法:

ListNode* swapPairs(ListNode* head) {
ListNode **pp = &head, *a, *b;
while ((a = *pp) && (b = a->next)) {
a->next = b->next;
b->next = a;
*pp = b;
pp = &(a->next);
}
return head;
}


输入一个链表

node1 -> node2 -> node3 -> node4

值得注意的是代码段

*pp = b;
pp = &(a->next);


第一次循环结束的时候pp指向的是node1的next指针,在第二次循环中

*pp = b;


将node1的next赋值为node4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐