24. 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.
题目链接: 24. Swap Nodes in Pairs
算法描述:
由题意知,给定一个链表,我们将对链表中的元素相互交换位置,返回交换位置之后的链表。
我们注意到在链表中交换的元素位置为:1 和 2 交换,3 和 4 交换, 5 和 6 交换 ······ 我们构造新的链表头指针 retHead,将之前的头指针 head 作为遍历指针。若当前遍历得链表元素不为空,且它之后的链表元素也不为空时,交换遍历指针 head 的前后两个元素,之后,遍历指针 head 后移两位,继续遍历·······
遍历结束时返回头指针 retHead 。
代码:
/** * 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) { int temp; ListNode* retHead = head; while(head != NULL && head->next != NULL){ temp = head->val; head->val = head->next->val; head->next->val = temp; head = head->next->next; } return retHead; } };