203.移除链表元素、206.反转链表、24. 两两交换链表中的节点
203.移除链表元素-Easy
状态:已完成
// 203.移除链表元素
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 删除头结点
while(head != NULL && head->val == val){
ListNode* tmp = head;
head = head->next;
delete tmp;
}
// 删除非头结点
ListNode* cur = head;
while(cur != NULL && cur->next != NULL){
if(cur->next->val == val){
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else{
cur = cur->next;
}
}
return head;
}
};
206.反转链表-Easy
状态:已完成
代码随想录题解:
// 206.反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* tmp; // 保存cur的下一个节点
while(cur){
tmp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next
cur->next = pre; // 翻转操作
// pre指针和cur指针开始移动
pre = cur;
cur = tmp;
}
return pre;
}
};
24. 两两交换链表中的节点-Medium
状态:已完成
// 24. 两两交换链表中的节点
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);// 设置一个虚拟头结点
dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
ListNode* cur = dummyHead;
while(cur->next != NULL && cur->next->next != NULL){
ListNode* temp = cur->next; // 记录临时节点
ListNode* temp1 = cur->next->next->next; // 记录临时节点
cur->next = cur->next->next; // 步骤1
cur->next->next = temp; // 步骤2
cur->next->next->next = temp1; // 步骤3
cur = cur->next->next; // cur移动两位,准备下一轮交换
}
ListNode* result = dummyHead->next;
delete dummyHead;
return result;
}
};