Article Directory
Question: To delete a node specified value
Problem-solving ideas
A new head node can be easily processed.
C ++ code
/**
* 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;
}
};
Question: delete the specified node
Problem-solving ideas
Since only given node to be deleted, we do not know the predecessor of this node can not be deleted. However, the node is not the end node to be deleted, so you can make this value is set to rear-wheel drive node value of the node, then the node will be deleted after the flooding.
C ++ code
/**
* 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;
}
};
Question: Delete the sort the list of repeating elements
Problem-solving ideas
Since the list is ordered, thus equal to the value of the node adjacent to the node, so long as the comparison value is equal to the current node value to a node on the reservation.
C ++ code
/**
* 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;
}
};
Question: repeating elements II sort the list of deleted
Problem-solving ideas
Because of repeated elements you must delete all, so you can use a map <int, int> Record number of times each element appears, and then delete the duplicate elements can be.
C ++ code
/**
* 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;
}
};