1 题目:
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
2 参考:
3 代码:
C++
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* temp = dummyHead;
while (temp->next != nullptr && temp->next->next != nullptr) {
ListNode* node1 = temp->next;
ListNode* node2 = temp->next->next;
temp->next = node2;
node1->next = node2->next;
node2->next = node1;
temp = node1;
}
ListNode* ans = dummyHead->next;
delete dummyHead;
return ans;
}
};
Python3:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
PHead = ListNode(0)
PHead.next = head
cur = PHead
if head == None: return None
if head.next == None: return head
# cur = 0->1->2->3->4->...
while cur.next and cur.next.next:
cur1 = cur.next # cur1 = 1, 1->2->3->4->...
cur2 = cur.next.next # cur1 = 2, 2->3->4->...
cur.next = cur2 # cur = 0, 0->2->3->4->...
cur1.next = cur2.next # cur1 = 1, 1->3->4->...
cur2.next = cur1 # cur2 = 2, 2->1->3->4->...
cur = cur1 # cur = 1, 1->3->4->... 此时,1和2已经交换了,cur指向1
return PHead.next