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.
解法一:递归
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* new_head = head->next;
head->next = swapPairs(new_head->next);
new_head->next = head;
return new_head;
}
};
解法二:非递归
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* new_head = NULL;
ListNode** pp = &new_head;
while(head != NULL){
if(head->next == NULL){
*pp = head;
break;
}
else{
*pp = head->next;
head->next = (*pp)->next;
(*pp)->next = head;
pp = &(head->next);
head = head->next;
}
}
return new_head;
}
};
本文介绍了一种链表中相邻节点的交换算法,通过两种方法实现:递归和非递归方式。递归方法简洁直观,而非递归方法则通过循环来完成节点的交换,两种方法均只使用常数空间,不改变列表中的数值,仅调整节点位置。
524

被折叠的 条评论
为什么被折叠?



