第十三周算法

来源:互联网 发布:win7网络驱动下载 编辑:程序博客网 时间:2024/05/20 16:40

题目:

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.

Subscribe to see which companies asked this question.


解答:

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;}