Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4 , you should return the list as 2->1->4->3 .
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
這題不難,但需要畫一下圖來釐清怎麼變換指標
配合圖,應該就可以寫得出來
code 如下
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
} | |
} | |
} | |
} |
沒有留言:
張貼留言