数据结构之链表实现与操作(java实现)

一、链式存储

        链式存储是数据结构中最重要的存储结构之一,也是后续学习树,图数据结构的基础,在本文中以最简单的单链表为例,讨论链表最基本的操作以及用途


二、单链表的基本操作

    1、数据结构(存储)

        单链表节点的两个域:数据域+指针域(存放下一个节点的地址)

        private class Node{
		
		int data;
		Node next;
	}
	
	Node Elem;

    2、单链表最基本操作之插入操作

        

        //在链表后插入指定 数
	public void insertList(int n) {
		
		Node tmp;
		Node newNode;
		
		newNode=new Node();
		newNode.data=n;
		newNode.next=null;
		
		for(tmp=Elem;tmp.next!=null;tmp=tmp.next);
		
		tmp.next=newNode;
			
	}

     3、单链表最基本操作之删除操作

        //删除指定数据的链表节点
	public void deleteList(int data) {
		
		Node tmp;
		Node pre;
		
		if(isEmpty())
			System.out.println("链表已空,无法删除");
		
		for(pre=Elem,tmp=Elem.next;tmp!=null;pre=tmp,tmp=tmp.next) {
			
			if(tmp.data==data) {
				pre.next=tmp.next;
				break;
			}
			
		}
		
		if(tmp==null)
			System.out.println("该数据节点不存在");
			
		
	 }


三、综合程序展示

        LinkList.java

        

    package LinkList;

    public class LinkList {
	
	private class Node{
		
		int data;
		Node next;
	}
	
	Node Elem;
	
	//创建头节点为空的链表
	public LinkList() {
		
		Elem=new Node();
		Elem.next=null;
	}
	
	public boolean isEmpty() {
		
		if(Elem.next==null)
			return true;
		else
			return false;
		
	}
	
	//在链表后插入指定 数
	public void insertList(int n) {
		
		Node tmp;
		Node newNode;
		
		newNode=new Node();
		newNode.data=n;
		newNode.next=null;
		
		for(tmp=Elem;tmp.next!=null;tmp=tmp.next);
		
		tmp.next=newNode;
			
	}
	
	//删除指定数据的链表节点
	public void deleteList(int data) {
		
		Node tmp;
		Node pre;
		
		if(isEmpty())
			System.out.println("链表已空,无法删除");
		
		for(pre=Elem,tmp=Elem.next;tmp!=null;pre=tmp,tmp=tmp.next) {
			
			if(tmp.data==data) {
				pre.next=tmp.next;
				break;
			}
			
		}
		
		if(tmp==null)
			System.out.println("该数据节点不存在");
			
		
	}

	public void showList() {
		
		Node tmp;
		
		for(tmp=Elem.next;tmp!=null;tmp=tmp.next)
			System.out.print(tmp.data+"  ");
		
		System.out.println();
	}
}

            

   附:介于作者理解与编码能力有限,欢迎各位前辈批评指正

         本文为作者原创,转载请说明出处

猜你喜欢

转载自blog.csdn.net/qq_36441169/article/details/80758986