给一个循环已排序链表,给一个需要插入的int值
需要注意三点:
如果插入的值大于最大值或者小于最小值。
给的head不一定是最小值,也就是说,给的head不一定是最后应该返回的头。
在已排序的链表中有可能出现重复。
private static LinkedList InsertCycle(LinkedList head, int insertN) {
// TODO Auto-generated method stub
//给的头结点不一定是最小的。需要自己找一下开头
//可能有重复
if(head == null)
{
LinkedList M = new LinkedList(insertN);
return M;
}
LinkedList p =head.next;
int min = head.val;
LinkedList newhead = head;
int count = 1;
while(head != p)//找到最小值,并且设置它为head
{
if(min > p.val)
{
min = p.val;
newhead = p;
}
count++;
p = p.next;
}
p = newhead;
head = newhead;
int countBig= 0;
if(insertN < p.val)
{
LinkedList minN = new LinkedList(insertN);
for(int j = 0; j< count-1; j++)
{
p = p.next;
}
minN.next = p.next;
p.next = minN;
p = p.next;
head = p;
}
else
{
for(int i=0; i < count; i++)
{
if(insertN > p.val && insertN <= p.next.val)
{
LinkedList newNode = new LinkedList(insertN);
newNode.next = p.next;
p.next = newNode;
break;
}
if(insertN > p.val)//如果大于最大值
{
countBig++;
if(countBig == count)
{
LinkedList newNode = new LinkedList(insertN);
newNode.next = p.next;
p.next = newNode;
break;
}
}
p = p.next;
}
}
return head;
}