Java实现链表

常见的链表有单向链表、双向链表、循环链表;现在依次给予实现,具体文字以后描述慢慢写

1、单向链表

package com.ccy.struct;

public class LinkList<T> {
	
	/** 节点 */
	private class Node {
		
		private T data;
		private Node next;
		
		public Node(T data, Node next) {
			this.data = data;
			this.next = next;
		}
	}
	
	private Node header; // 头结点
	
	private Node tail;	// 尾结点
	
	private int size;

	public LinkList() {
		header = null;
		tail = null;
	}
	
	public int length() {
		return size;
	}
	
	public boolean isEmpty() {
		return size == 0;
	}
	
	/** 增加  */
	public LinkList<T> add(T element) {
		if (header == null) { // 空链表
			header = new Node(element, null);
			tail = header;
		} else { // 非空链表
			Node newNode = new Node(element, null);
			tail.next = newNode;
			tail = newNode;
		}
		size++;
		return this;
	}
	
	private Node getNodeByIndex(int index) {
		if (index < 0 || index > size - 1) {
			throw new IndexOutOfBoundsException("索引越界");
		}
		Node currentNode = header;
		for (int i = 0; i < size && currentNode != null; i++, currentNode = currentNode.next) {
			if (i == index) {
				return currentNode;
			}
		}
		return null;
	}
	
	public T delete(int index) {
		if (index < 0 || index > size - 1) {
			throw new IndexOutOfBoundsException("索引越界");
		}
		Node del = null;
		if (index == 0) {
			del = header;
			header = header.next;
		} else {
			Node prev = getNodeByIndex(index - 1);
			del = prev.next;
			
			prev.next = del.next;
			del.next = null;
		}
		size--;
		return del.data;
	}
	
	public void clean() {
		header = null;
		tail = null;
		size = 0;
	}
	
	public String toString() {
		if (isEmpty()) {
			return "[]";
		} else {
			StringBuffer sb = new StringBuffer("[");
			for (Node currentNode = header; currentNode != null; currentNode = currentNode.next) {
				sb.append(currentNode.data.toString() + ", ");
			}
			int len = sb.length();
			return sb.delete(len - 2, len).append("]").toString();
		}
	}
}

测试类

public class App {
	
	public static void main(String[] args) {
		LinkList<String> list = new LinkList<String>();
		list.add("ccy")
			.add("xfh")
			.add("yk");
		System.out.println(list.toString()); // [ccy, xfh, yk]
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值