链表的基础知识点

27 篇文章 0 订阅

今天我们利用JAVA来实现一个单链表,

其中包括链表的结构,以及链表的基本操作。

整个类的设计:

public class Linked <T>{
	
	private class Node{
		private T t;
		private Node next;
		public Node(T t,Node next){
			this.t = t;
			this.next = next;
		}
		public Node(T t){
			this(t,null);
		}
	}
	private Node head;    		//头结点
	private int size;			//链表元素个数
	//构造函数
	public Linked(){
		this.head = null;
		this.size = 0;
	}
}

常见的基本操作:

添加:

头插法:

public void addfirst(T t){
  Node node = new Node(t);
  node.next = this.head;
  this.head = node;
  this.size++;
}

尾插法:

public void addlist(T t){
  this.add(t,this.size);
}

向链表中间插入元素:

public void add(T t,int index){
  if(index < 0 || index > size){
     throw new IllegalArgumentException("index is error"); 
 }
  if(index == 0){
     this.addfirst(t);
       return;  
 }
  Node preNode = this.head;  //找到要插入结点的位置;
   for(int i = 0;i < index-1;i++){
     preNode = preNode.next; 
  }
   
  Node node = new Node(t);
   node.next = preNode.next;
   preNode.next = node;
    this.size++;  
}

删除:

public void remove(T t){
  if(head == null){
   System.out.println("无元素");
    return;
}
   while(head != null && head.t.equals(t)){//删除头元素 
    head = head.next;
     this.size--;   
}

   Node del = this.head;
   while(del != null && del.next != null){
    if(del.next.t.equals(t)){
     this.size--;
     del.next = del.next.next;
      }
    else  del = del.next;
   }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值