219. 在排序链表中插入一个节点
在链表中插入一个节点。
样例
样例 1:
输入:head = 1->4->6->8->null, val = 5
输出:1->4->5->6->8->null
样例 2:
输入:head = 1->null, val = 2
输出:1->2->null
代码区:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution
{
/**
* @param head: The head of linked list.
* @author :username:softstarhhy
* @param val: An integer.
* @return: The head of new linked list.
*/
//根据head和插入位置来进行对应操作
public ListNode insertNode(ListNode head, int val)
{
int nums=1;
int loc= Getlocnum( head,val);
//为空节点时操作 需要创建并插入第一个位置
if(loc==0&&head==null)
{
ListNode listnode=new ListNode(val);
head=listnode;
return head;
}
//为1个节点时 且目标值比已知节点的值还小 需要比较插入到第一个位置 其中比较操作已在Getlocnum方法中实现
if(loc==0&&head!=null)
{
ListNode listnode2=new ListNode(val);
listnode2.next=head;
head=null;
head=listnode2;
return head;
}
ListNode p=head;
ListNode q=head.next;
//除以上两种情况外的情况
while(p!=null)
{
if(nums<loc)
{
nums++;
p=q;
q=q.next;
}else if(nums==loc)
{
ListNode newlistnode=new ListNode(val);
newlistnode.next=p.next;
p.next=newlistnode;
p=newlistnode;
return head;
}else
{
}
}
return head;
}
//找到插入位置
public int Getlocnum(ListNode head,int val)
{
int nums=0;
if(head==null)
{
return 0;
}
while(head!=null)
{
if(val<head.val)
{
return nums;
}else
{
nums++;
head=head.next;
if(head==null)
{
return nums;
}
}
}
return nums;
}
}