2016年12月2日 星期五

[LeetCode] 24. Swap Nodes in Pairs

轉自LeetCode

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.
<Solution>

這題不難,但需要畫一下圖來釐清怎麼變換指標

配合圖,應該就可以寫得出來

code 如下
c++
/**
* 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) {
if(!head || head->next == NULL) {
return head;
}
ListNode *dummy = new ListNode(0);
ListNode *curr = dummy, *tmpNode = NULL;
dummy->next = head;
while(curr->next && curr->next->next) {
tmpNode = curr->next->next;
curr->next->next = tmpNode->next;
tmpNode->next = curr->next;
curr->next = tmpNode;
curr = tmpNode->next;
}
return dummy->next;
}
};

kotlin
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun swapPairs(head: ListNode?): ListNode? {
return when {
head == null -> null
head!!.next == null -> head
else -> {
val left = head
val right = head!!.next
left.next = swapPairs(right!!.next)
right.next = left
right
}
}
}
}

沒有留言:

張貼留言