这道题应该是一道编程语言题,因为要解决的问题是链表的操作。原题链接
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指针,那么就会变得如红线所示。
这时候,最后一个节点就会变成了不可访问的节点了。
因此,我们进行这个操作的时候需要使用的到是3个临时指针。
cpp源码:
/**
* 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* l;
ListNode* p;
ListNode* q;
p = head;
l = head;
while (true) {
if (p == NULL) {
break;
}
else {
q = p->next;
}
if (q == NULL) {
break;
}
p->next = q->next;
q->next = p;
if (p == head) {
head = q;
}
else {
l->next = q;
}
l = p;
p = p->next;
}
return head;
}
};