有一个整数val,如何在节点值有序的环形链表中插入一个节点值为val的节点,并且保证这个环形单链表依然有序。
给定链表的信息,及元素的值A及对应的nxt指向的元素编号同时给定val,请构造出这个环形链表,并插入该值。
[1,3,4,5,7],[1,2,3,4,0],2
返回:{1,2,3,4,5,7}
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class InsertValue {
public:
ListNode* insert(vector<int> A, vector<int> nxt, int val) {
// write code here
ListNode *now=new ListNode(val);
ListNode *head=new ListNode(A[0]);
ListNode *p=head;
int n=A.size();
if(n==0)
return now;
for(int i=1;i<n;i++)
{
ListNode *q=new ListNode(A[i]);
p->next=q;
p=p->next;
}
p->next=head;
if(val <= head->val){
p = head;
while(p->next != head)
p = p->next;
p->next = NULL;
now->next = head;
head = now;
return head;
}
p = head;
while((p->next->val)<val){
if(p->next == head){
p->next = now;
now->next = NULL;
return head;
}
p = p->next;
}
ListNode* q = p->next;
p->next = now;
now->next = q;
p = head;
while(p->next != head)
p = p->next;
p -> next = NULL;
return head;
}
};