24. 两两交换链表中的节点
1.在while循环中进行temp和temp1的定义
通常设置临时节点来解题
-转自代码随想录
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;
}
};
19.删除链表的倒数第N个节点
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
1.fast!=null 和 fast!=nullptr通常是一样的
-转自代码随想录
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead=new ListNode(0);
dummyhead->next=head;
ListNode* slow=dummyhead;
ListNode* fast=dummyhead;
while(n--&&fast!=NULL){
fast=fast->next;
}
fast=fast->next;
while(fast!=NULL){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return dummyhead->next;
}
};