剑指 Offer II 029. 排序的循环链表

链表节点插入

关键是判断临界点,假设整个链表为顺序表,那么我们在这个表中插入,有三种情况

  1. 在顺序表中

  1. 表头

  1. 表位

然而在循环链表中,表头与表尾的位置是相同的,所以我们注重关于与插入节点本身,以及临界点的判定上

/*
// 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值