описание
Учитывая обмен список попарно с соседними узлами, и возвращает список обмена.
Вы не можете просто изменить значение внутренних узлов, но должны быть фактическим обменом узла.
Примеры
идей
- Рекурсивный: чтобы определить, является ли пустой, или только один узел узел, в противном случае, сохранить второй, не сохраняются, не может найти его, если пресса операция, наконец, возвращение в секунду
- Итерация
ответ - питон
*递归*
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;
}
};