Delete duplicate elements in the sorted list II
Problem Description
Given a sorted linked list, delete all nodes with repeated numbers, and only keep the numbers that do not appear repeatedly in the original linked list.
Problem-solving ideas
/**
* 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* deleteDuplicates(ListNode* head) {
ListNode* pre_head = new ListNode(0,head);
ListNode* cur = pre_head;
while(1){
if(!cur->next||!cur->next->next)//若下一个结点或下下一个结点为空,则不用交换
break;
else{
int flag = 0;//用来标志当前结点是否为重复结点,初始时都假设不重复
ListNode* p = cur->next;
ListNode* q = p->next;
if(p->val == q->val){
//若有重复,则删除
ListNode* temp = q;
p->next = q->next;
q = temp->next;
delete temp;
flag = 1;//标记该节点为重复的
}
if(flag == 1 && (!q || p->val != q->val)){
//删除该重复节点
cur->next = q;
delete p;
}
if(flag == 0)//不重复,则cur指针后移
cur = cur->next;
}
}
return pre_head->next;
}
};
Recursive thinking:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) {
//递归结束的条件
return head;
}
if (head->val == head->next->val) {
//若有重复
while (head && head->next && head->val == head->next->val) {
//跳过所有的重复结点
head = head->next;
}
return deleteDuplicates(head->next);
} else {
//无重复
head->next = deleteDuplicates(head->next);
return head;
}
}
};
Split list
Problem Description
Given a linked list and a specific value x, please separate the linked list so that all nodes less than x appear before nodes greater than or equal to x.
You should keep the initial relative position of each node in the two partitions.
Problem-solving ideas
Maintain a small and big linked list, connect all nodes less than x to the small linked list, connect all nodes greater than or equal to x to the big linked list, and finally connect the big linked list to the back of the small linked list.
/**
* 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* partition(ListNode* head, int x) {
ListNode* big_head = new ListNode();
ListNode* big_cur = big_head;
ListNode* small_head = new ListNode();
ListNode* small_cur = small_head;
while(head){
if(head->val < x){
small_cur->next = head;
small_cur = small_cur->next;
head = head->next;
}else{
big_cur->next = head;
big_cur = big_cur->next;
head = head->next;
}
}
small_cur->next = big_head->next;
big_cur->next = nullptr;
return small_head->next;
}
};