代码随想录第四天 2023.7.15
题目链接:
24. 两两交换链表中的节点 - 力扣(Leetcode)https://leetcode.cn/problems/swap-nodes-in-pairs/
代码如下:
/**
* 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);
ListNode* cur=dummyHead;
dummyHead->next = head;
while(cur->next!=nullptr&&cur->next->next!=nullptr){
ListNode* temp=cur->next;
ListNode* temp1=cur->next->next->next;
cur->next=cur->next->next;
cur->next->next=temp;
cur->next->next->next=temp1;
cur=cur->next->next;
}
return dummyHead->next;
}
};
注意:
1.temp和temp1指针的含义:
temp指向原链表中第一个节点,temp1指向原列表中第三个节点,第二个节用cur->next直接指定;在交换链表操作中,链表前先定义了一个虚拟头节点 dummyHead->next = head; 将虚拟头结点指向head,这样方面后面做删除操作
第一次写代码时落掉了这一部操作,导致程序运行超时
2.while的判断条件中两条语句的顺序不能交换,因为cur->next为空时,判断cur->next->next会空指针报错
3.cur指针后移两位的操作:
cur=cur->next->next;