给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路1:提前定义了三个节点,感觉会好理解一点
ListNode254* swapPairs(ListNode254* head) {
//初始化一个虚拟节点
ListNode254* dummyHead = new ListNode254(0);
//将虚拟节点与头结点连接起来:
dummyHead->next = head;
//当头节点为空,就直接返回空结点
//当头结点的下一个结点为空,就意为这链表中只有一个结点,此时也不用两两交换了,直返回那个结点就行;
if (head == nullptr || head->next == nullptr)
return head;
//要交换结点,需要提前准备好3个结点;
//pre是需要交换的两个结点之前的结点:
ListNode254 *pre = dummyHead;
//需要交换的两个结点中的第一个结点:
ListNode254* first = head;
//需要交换的两个结点中的第二个结点:
ListNode254* second = head->next;
//first结点和second结点均不为空,就意味着链表中至少有两个结点:
while (first&&second ) {
//交换节点
//step1:
pre->next = second;
//step2:
first->next = second->next;
//step3:
second->next = first;
//指针向后移动
pre = first;
first =first->next;
if(first==nullptr)
return dummyHead->next;
second = first->next;
}
//必须return dummyHead的下一个结点,因为head在交换之后会发生变化:
return dummyHead->next;
}
思路1:未提前定义节点,但是过程简介
ListNode254* swapPairs1(ListNode254* head) {
ListNode254 * dummyNode = new ListNode254(0);
ListNode254* cur = dummyNode;
dummyNode->next = head;
while(cur->next&&cur->next->next){
ListNode254* temp1 = cur->next;
ListNode254* temp2 = cur->next->next->next;
//step1:
cur->next = cur->next->next;
//step2:
cur->next->next = temp1;
//step3:
temp1->next = temp2;
//cur向后移动两位
cur = cur->next->next;
}
return dummyNode->next;
}