單鏈表操作--java

        單鏈表的簡單操作,包括新增頭結點、刪除頭結點、在任意位置新增節點、在任意位置刪除節點、通過節點位置刪除節點、通過數據域中的數刪除節點。

       注意事項:

1、添加操作:若該鏈表爲空,則不應該插入非頭節點,若該鏈表不爲空,不允許插入超出鏈表長度的數據,如鏈表長度爲2,則鏈表位置爲0,1,此時插入數據最大位置爲2,不允許插入數據位置設爲3.

2、刪除操作:若該鏈表爲空,不允許進行刪除操作,若該鏈表不爲空,不允許哎刪除操作時傳值位置超出鏈表長度,利用數值查詢進行刪除,若傳值的數據不存在,無法進行刪除。

      具體代碼如下:有什麼寫的不周全的歡迎指正。

package List;

public class LinkList {

	public Node first;   //定義一個頭結點
	public int temp=0;    //頭結點的位置
	int len=0;
	 
	//構造函數,頭結點初始狀態的的指針域指向空
	public LinkList()
	{
		this.first=null;
	}
	
	//插入一個頭結點
	public void addFirstNode(int data)
	{
		Node node=new Node(data);
		node.next=first;   //新建的節點的指針域點指向原頭結點
		first=node;        //頭結點變爲node
		len++;
	}
	
	//刪除一個頭結點,並返回頭結點
	public Node deleteFirstNode()
	{
		Node temp=null;
		if(first==null)
			System.out.println("刪除失敗,該鏈表爲空,不可執行刪除操作");
		else
		{
		temp=first;
		first=temp.next;
		len--;
		}
		return temp;
	}
	
	//在任意位置插入節點,該位置由傳參index決定,新增節點爲index位置
	public void add(int index,int data)
	{
		Node node=new Node(data);
		Node previous=first;
		Node current=first;
		if(index>len)
		{
			System.out.println("插入失敗,插入數據位置超出該鏈表長度");
			return;
		}
		while(temp!=index)
		{
			previous=current;
			current=current.next;
			temp++;
		}
		if(index==0)
		{
			node.next=first;
			first=node;
		}
		else
		{
		node.next=current;
		previous.next=node;
		}
	    temp=0;
	    len++;
	}
	
	
	//刪除任意位置的節點,並返回該節點
	public Node delete(int index)
	{
		Node current=first;
		Node previous=first;
		if(index>len)
		{
			System.out.println("刪除失敗,該節點位置不存在鏈表中,超出鏈表");
			return null;
		}
		while(temp!=index)
		{
			previous=current;
			current=current.next;
			temp++;
		}
		if(current==first)
			first=first.next;
		else
			previous.next=current.next;
		temp=0;
		len--;
		return current;
	}
	
	//根據data刪除該節點,並返回該節點
	public Node deleteByData(int data)
	{
		Node current=first;
		Node previous=first;
		while(current.data!=data)
		{
			if(current.next==null)
			{
				System.out.println("刪除失敗,該數據不存在與該鏈表中");
				return null;
			}
			previous=current;
			current=current.next;
			
		}
		if(current==first)
		{
			first=current.next;
		}
		else
			previous.next=current.next;	
		len--;
		return current;	
		}
	
	//顯示所有的節點信息
	public void displayALL()
	{
		Node current=first;
		while(current!=null)
		{
			current.display();
			current=current.next;
		}
		
	}
	
	public static void main(String[] args)
	{
		LinkList list=new LinkList();
		list.displayALL();
		list.addFirstNode(1);
		list.addFirstNode(10);
		list.add(2,2);
		list.add(2,3);
		list.add(3,4);
//		list.add(5,13);
//		list.deleteFirstNode();
//		list.delete(8);
//		list.deleteByData(3);
		list.displayALL();
	}

}



package List;

public class Node {
 protected Node next;
 protected int data;
 
 public Node(int data)
 {
	 this.data=data;
 }

public void display()
 {
	 System.out.print(data + " ");
 }
 
}





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