题目描述:
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.
要交换成对的节点的位置,唯一变化的其实只有节点的值,指针可以不用修改。
于是直接从处理,将当前节点的值与下一个节点交换,然后往后移动两个节点继续相同的处理即可。这对于最后落单的直接就不会处理
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.
Hide Tags Linked List
要交换成对的节点的位置,唯一变化的其实只有节点的值,指针可以不用修改。
于是直接从处理,将当前节点的值与下一个节点交换,然后往后移动两个节点继续相同的处理即可。这对于最后落单的直接就不会处理
以下是C++实现代码:
*///////4ms////////*/
/**
* 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 *tmp = head;
while(tmp != NULL && tmp->next != NULL) //从头节点开始,依次处理每对节点,只交换节点的元素值
{
int v = tmp->next->val;
tmp->next->val = tmp->val;
tmp->val = v;
tmp = tmp->next->next;
}
return head;
}
};