文章目录
问题:删除指定值的节点
解题思路
新增一个头节点可以方便处理。
C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *list = new ListNode(0);//增加一个头节点
ListNode *tail = list, *cur = head;
while(cur){
if(cur->val != val){//不是待删除的节点
tail->next = cur;
tail = cur;
cur = cur->next;
}
else{//是待删除的节点
ListNode *tmp = cur->next;
delete cur;//删除此节点
cur = tmp;
}
}
tail->next = NULL;
return list->next;
}
};
问题:删除指定节点
解题思路
由于只给定了待删除的节点,我们不知道此节点的前驱节点,因此无法删除。但是,由于待删除节点不是尾节点,因此可以让此节点的值设为后驱节点的值,然后将后驱节点删除即可。
C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
ListNode *tmp = node->next;
node->next = node->next->next;
delete tmp;
}
};
问题:删除排序链表中的重复元素
解题思路
由于是有序链表,因此节点值相等的节点相邻,因此只要比较当前节点的值是否等于上一个保留的节点的值即可。
C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) return head;
ListNode *tail = head, *cur = head->next;
while(cur){
if(cur->val != tail->val){//不重复,加入此节点
tail->next = cur;
tail = cur;
cur = cur->next;
}
else{//重复
ListNode *tmp = cur->next;//记录下一个节点
delete cur;
cur = tmp;
}
}
tail->next = NULL;//tail是最后一个节点
return head;
}
};
问题:删除排序链表中的重复元素 II
解题思路
由于重复的元素必须全部删除,因此可以使用一个map<int,int>记录每个元素出现的次数,然后删除重复的元素即可。
C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
map<int, int>dict;//记录各个数字出现的次数
ListNode *cur = head;
while(cur){
dict[cur->val]++;
cur = cur->next;
}
//新建一个头节点,方便处理
ListNode *list = new ListNode(0), *tail = list;
cur = head;
while(cur){
if(dict[cur->val] > 1){ //是重复的,删除
ListNode *tmp = cur->next;
delete cur;
cur = tmp;
}
else{ //不是重复的
tail->next = cur;
tail = cur;
cur = cur->next;
}
}
tail->next = NULL;//重要,tail是最后一个节点 !!!!
return list->next;
}
};