LeetCode 708. 循环有序列表的插入*

具体思想:

我草她妈,这个题真的太恶心了,全是边界,不难就纯恶心人;

注意一下边界条件:
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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值