題目描述:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
代碼:
/**
* 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 index = 1;
ListNode* current = head;
ListNode* first;
while(current != NULL){
if(index % 2 != 0){
first = current;
current = current -> next;
}
else{
int fValue = first -> val;
first -> val = current -> val;
current -> val = fValue;
current = current -> next;
}
index++;
}
return head;
}
};
此題目歸爲Medium有點過分感覺,稍微有點鏈表知識的人都知道是很水的一道題,兩兩互換值,只需要每次保存一下奇數位(起始位置爲1)節點然後在偶數位互換val即可。