الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

شو الغلط في insertAtHead في ال ListNode

مغلق
بدأه mkd في 10 أبريل 2006 · 2 رد · 466 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

ممكن يا جماعة الخير تشوفولي شو الغلط في insertAtHead في ال ListNode التالية

لانو في التست لما بدي اضيف نود جديدة و اطلبع الأوبجكت اللي فيها ما بيخرجو و بيطبع Null في جميع الحالات ..

مع العلم انو insertNewSecondNode و كذلك insertLast شغالين مية مية

public class LinkedList
{
	protected Node head;
	protected int length;

	public LinkedList()
	{
  head=null;
  length =0;
	}


	public int size ()
    {
    return length;
	}

	public void print()
	{
  
  
  Node n;
  n=head;
  
  while (n!= null)
  {
 	 System.out.println(n.data);
 	 n=n.next;
  }
  
  System.out.println("NUMBER OF ELEMENTS IN THE LIST = "+size()+"\n");
  
	}


  
	public Object getData(int index  )
	{
  Node p = head;
         	 
  if (index<1 || index >length)
  return null;
  
  else 
  for (int i =2;i<=length;i++)
  p=p.getNext();
  return p.getData();
  
	}



    // adding data at first ..
	public  void insertAtHead(Object obj)
	{

        Node mkd= new Node(obj,head);
        this.head = mkd;

    length ++;
	}




	//  adding data at the second place ..
     public void insertNewSecondNode(Object o)
    {
   	 
   	 if(length == 0 ) return;
   	 
   	 Node newNode = new Node();
   	 
   	 newNode.data= o;
      newNode.next = head.next;
   	 head.next = newNode;
   	 
   	 length ++;
   	 
   	 
    }
    
    
    // adding data in the last ..
    
    public void insertLast(Object o)
    {
   	 Node newNode = new Node();
   	 
   	 newNode.data=o;
   	 newNode.next= null;
   	 
   	 
   	 if (head ==null)
   	 head = newNode;
   	 
   	 else
   	 {
      Node p = head;
      while (p.next != null)
      p=p.next;
      
      p.next=newNode;
      
   	 }
   	 
   	 length ++;
   	 
   	 
    }
    
    
    
    
    //delete the las node in the list ..
    public void deleteLast()
    {
   	 
   	 Node current , prev;
   	 
   	 if (head != null)
   	 {
      
   	 if (head.next == null)
   	 {
      head = null;
      length --;
   	 }	
   	 
   	 else
      
      {
       prev =head;
       current = head.next;
             while (current.next != null)
             {
              prev=current;
              current=current.next;
             }
             prev.next=null;
             length--;
             
      }
      
      
      
      
   	 }
   	 
   	 
    }

}
#2

up

#3

و عندك كمان Up

هذا الموضوع مغلق.

مواضيع مشابهة