问题:Swap Nodes in Pairs
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.
这个问题其实不难理解,就是要在链表中不停做元素位置的交换。我们需要一个临时指针和两个指针分别之前当前节点和下一节点。交换两者的操作比较基础,把前一节点的next设置为后节点的next,然后后节点的next设置成前节点。昨晚这一步后,整体后移。直到链表尽头。代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: 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; } };
