使用虚拟节点来进行操作,注意cur的位置需要在每次操作的两个数值的前一位
C++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* cur = dummyhead;
//注意这里先是cur->next,而后再是cur->next->next,如果二者倒换的话,假使cur->next为空的话,那么cur->next->next是不正确的,程序会出现问题
while(cur->next!=nullptr&& cur->next->next != nullptr)
{
ListNode* tmp = cur->next;
ListNode* tmp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
tmp->next = tmp1;
cur = cur->next->next;
}
ListNode* result = dummyhead->next;
delete dummyhead;
return result;
}
};
Python:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
dummyhead = ListNode(next = head)
cur = dummyhead
while cur.next!=None and cur.next.next != None:
tmp = cur.next
tmp1 = cur.next.next.next
cur.next = cur.next.next
cur.next.next = tmp
tmp.next = tmp1
cur = cur.next.next
return dummyhead.next
C:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head)
{
struct ListNode* dummyhead = (struct ListNode*)malloc(sizeof(struct ListNode));
dummyhead->val = 0;
dummyhead->next = head;
struct ListNode* cur = dummyhead;
while(cur->next != NULL && cur->next->next != NULL)
{
struct ListNode* tmp = cur->next;
struct ListNode* tmp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
tmp->next = tmp1;
cur = cur->next->next;
}
struct ListNode* result = dummyhead->next;
free(dummyhead);
return result;
}