lintcode算法題之219-在排序鏈表中插入一個節點

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;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章