链表节点插入
关键是判断临界点,假设整个链表为顺序表,那么我们在这个表中插入,有三种情况
在顺序表中
表头
表位
然而在循环链表中,表头与表尾的位置是相同的,所以我们注重关于与插入节点本身,以及临界点的判定上
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node() {}
// 赋值构造
Node(int _val) {
val = _val;
next = NULL;
}
// 插入构造
Node(int _val, Node* _next) {
val = _val;
next = _next;
}
};
*/
class Solution {
public:
Node* insert(Node* head, int insertVal) {
// 没有节点与一个节点的时候
if(head == NULL){
Node* p =new Node(insertVal);
head = p;
head->next = head;
return head;
}
if(head->next == head){
Node* p =new Node(insertVal,head);
head->next = p;
return head;
}
// 寻找链表中的最大值和最小值,方便定位假定顺序表的表头和表尾
int max_v = head->val;
int min_v = head->val;
Node* p = head->next;
Node* q = head;
while(p){
if(p==q) break;
else{
max_v = max(max_v,p->val);
p=p->next;
}
}
p = head->next;
while(p){
if(p==q) break;
else{
min_v = min(min_v,p->val);
p = p->next;
}
}
p = head;
// 寻找合适额插入位置
while(p){
// 第一种情况,恰好顺序在两个值中间
if(insertVal>=p->val&&insertVal<=p->next->val){
// 插入到q的后面
Node* q =new Node(insertVal,p->next);
p->next=q;
return head;
}else if(insertVal>=p->val&&insertVal>=p->next->val&&p->val==max_v&&p->next->val == min_v){ // 第二种情况,插入的值在升序表的尾部
//插入值为最大值时 看当前位置是否是假定顺序表表头
Node *q =new Node(insertVal,p->next);
p->next=q;
return head;
}else if(insertVal<p->val&&insertVal<p->next->val&&p->val==max_v&&p->next->val == min_v){// 第三种情况,在升序表的头部
// 插入值为最小值时,看当前位置是否是假定顺序表表头
Node *q =new Node(insertVal,p->next);
p->next=q;
return head;
}else{
p = p->next;
}
}
return head;
}
};