java实现单链表基本操作

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/onlyoncelove/article/details/79546574

    用java语言实现单链表的基本操作。。。。

public class Mylink {
	
	private int length;
	private Node head;
	private Node rear;
	private Node p;
	
	private class Node{
		private Object data;
		private Node next;
		
		public Node(){
			this.data = null;
		}
		
		public Node(Object e){
			this.data = e;			
		}
	}
	
	
	//创建不带数据的头节点
	public Mylink(){
		head = new Node();
		rear = head;
		head.next = null;
		length = 0;
	}
	
	//头插法创建链表
	public void addNode(Object e){
		
		if(head==null){
			head = new Node();
			return;
		}
		Node node = new Node(e);
		node.next = head.next;
		head.next = node;
		length++;
	}
	
	//尾插法创建链表
	public void addNodeInRear(Object e){
		if(head==null){
			head = new Node();
			return;
		}
		
		Node node = new Node(e);
		node.next = null;
		rear.next = node;
		rear = node;
		length++;
	}
	
	//在第i位置插入值e
	public void insert(int i,Object e){
		if(head==null){
			return ;			
		}
		p = head;
		int j = 0;
		while(p!=null){
			j++;
			if(j==i){
				Node node = new Node(e);
				node.next = p.next;
				p.next = node;		
				length++;
				break;
			}
			
			p = p.next;
		}
		
	}
	
	//删除第i个节点
	public void deleteNode(int i){
		if(head == null){
			return ;
		}
		int j = 0;
		p = head;
		while(p.next!=null){
			j++;
			if(j == i){
				p.next = p.next.next;
				length--;
				break;
			}
			
			p=p.next;
		}
	}
	
	//求当前链表的长度为
	
	public int linkLenth(){
		return length;
	}
	
	
	//打印链表
	public void print(){
		p = head.next;
		while(p!=null){
			System.out.print(p.data+"\t");
			p = p.next;
		}
		System.out.println();
	}
	
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Mylink link = new Mylink();
		
		System.out.println("链表的初始值为:");
		link.addNodeInRear(5);
		link.addNodeInRear(6);
		link.addNodeInRear(10);
		
		
		
		link.print();
		link.insert(4, 3);
		System.out.println("插入值后的链表为:");
		link.print();
		
		//删除第i个位置的节点
		link.deleteNode(4);
		System.out.println("删除第i个位置节点后的链表为:");
		link.print();
		
		System.out.println("当前链表的长度为:"+link.linkLenth());
	}

}

展开阅读全文

没有更多推荐了,返回首页