description
Given a list pairwise exchange with adjacent nodes, and return the list to the exchange.
You can not just simply change the internal node values, but need to be the actual node exchange.
Examples of
ideas
- Recursive: to determine whether the node is empty, or only one node, otherwise, save second, not saved can not find it, if the press operation, finally, return to second
- Iteration
answer - python
*递归*
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
second=head.next
head.next=self.swapPairs(second.next)
second.next=head
return second
*迭代*
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
#因为要反转,所以给链表构造一个头结点
newHead = ListNode(0)
newHead.next = head
cur=newHead
while cur.next and cur.next.next:
# 因为改变链表的顺序,所以,先保存第一个不变的结点
first = cur.next
second = cur.next.next
first.next=second.next
second.next=first
cur.next=second
cur=cur.next.next
#如果还有一个结点,不用反转了
return newHead.next
- c++
*递归*
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
//如果为空,或者下一个结点为空,直接返回
if (!head || !head->next)
return head;
ListNode* second = head->next;
head->next = swapPairs(second->next);
second->next = head;
return second;
}
};
*迭代*
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* newHead = new ListNode(0);
newHead->next = head;
ListNode* cur=newHead;
while(cur->next && cur->next->next)
{
ListNode *first=cur->next, *second=cur->next->next;
first->next = second->next;
second->next = first;
cur->next = second;
cur=cur->next->next;
}
return newHead->next;
}
};