具体思想:
我草她妈,这个题真的太恶心了,全是边界,不难就纯恶心人;
注意一下边界条件:
1.单节点;
2.无节点;
3.全部相同元素节点,直接尾插;
4.所有节点小于插入元素;
5.所有节点大于插入元素;
6.节点可以插入在中间;
具体代码:
/*
// 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==nullptr){
head=new Node(insertVal);
head->next=head;
return head;
}
if(head->next==head){
Node* p=new Node(insertVal);
head->next=p;
p->next=head;
return head;
}
Node* pre=head;
while(pre->next!=head)
pre=pre->next;
Node* p=head;
if(p->val==pre->val){
Node* q=new Node(insertVal);
pre->next=q;
q->next=p;
return head;
}
while(1){
if((insertVal<=p->val&&insertVal>=pre->val)||(p->val<pre->val&&(p->val>insertVal||pre->val<insertVal))){
break;
}
p=p->next;
pre=pre->next;
}
Node* q=new Node(insertVal);
pre->next=q;
q->next=p;
return head;
}
};