java手动实现通用链表

链表做为一种重要的数据结构:分为单向链表、双向链表、双端链表、有序链表;这几种链表形式的区别在于遍历的方向,插入的方向,插入元素顺序等些方面的区别,其本质都一样,只要掌握链表的结构就能自己手动实现它。

package com.xd.mylink;

//单向链表
public class MyLink {

	private int size;

	private Node head;

	public class Node {

		Object data;

		Node next;

		public Node(Object data) {
			super();
			this.data = data;
		}

	}

	public MyLink() {
		super();
		this.head = null;
		this.size = 0;
	}

	public boolean isEmpty() {
		return this.head == null;
	}

	public int getSize() {
		return size;
	}

	// 在链表头增加
	public void addHead(Object obj) {
		Node node = new Node(obj);
		if (head == null) {
			head = node;
		} else {
			node.next = head;
			head = node;
		}
		size++;
	}

	// 在链表尾部增加
	public void addEnd(Object obj) {
		Node node = new Node(obj);
		Node n = head;
		if (head == null) {
			head = node;
		} else {
			while (true) {
				Node temp = n;
				n = n.next;
				if (n == null) {
					temp.next = node;
					break;
				}
			}
		}
		size++;
	}

	// 删除头部元素
	public void deleteHead() throws Exception {
		if (head == null) {
			throw new Exception("当前没有节点可删除");
		} else {
			head = head.next;
			size--;
		}
	}

	// 删除尾部元素
	public void deleteEnd() {
		Node node = head;
		Node temp = null;
		if (head == null) {
			System.out.println("当前链表没有节点,无法删除");
		} else {
			while (node.next != null) {
				temp = node;
				node = node.next;
			}
			temp.next = null;
			size--;
		}
	}

	// 根据值去删除
	public void deleteByObj(Object obj) {
		Node node = head;
		Node pre = null;
		if (node == null) {
			System.out.println("链表中无节点,无法删除");
		} else {
			// 先判断
			while (node != null && !(node.data == obj || node.data.equals(obj))) {

				pre = node;

				node = node.next;
			}
			if (pre == null) {
				// 删除的是头节点
				head = head.next;
			} else {
				if (node == null) {
					System.out.println("该值没有在链表中,删除失败");
				} else {
					pre.next = node.next;
				}
			}
			size--;
		}
	}

	public String toString() {
		Node node = head;
		String str = "";
		while (node != null) {
			str += (node.data + "->");
			node = node.next;
		}
		return str;
	}

}

-----------------------------------测试类------------------------------------------------
package com.xd.mylink;

public class MyLinkTest {

	public static void main(String[] args) throws Exception {
		MyLink link = new MyLink();
		link.addHead("b");
		link.addHead("a");
		link.addEnd("c");
		System.out.println(link.toString());
		System.out.println(link.isEmpty());
		System.out.println(link.getSize());
		//link.delete();
		//System.out.println(link.toString());
		//link.deleteByObj("d");
		//System.out.println(link.toString());
		link.deleteEnd();
		System.out.println(link.toString());
		System.out.println(link.getSize());
	}
}

---输出结果---
a->b->c->
false
3
a->b->
2

 

你可能感兴趣的:(java手动实现通用链表)