单链表java简易实现
巩固数据结构 单链表java实现 单链表除了表尾 每个几点都有一个后继 结点有数据和后继指针组成 通过构建表头和表尾(尾部追加需要)两个特殊几点 实现单链表的一些操作,代码如下
package com.shine.test.datastruct; /** * 简易链表 * * @author SHINE * * @param <E> */ public class LinkList<E> { private Node head, tail; private int size = 0; protected class Node<E> { E data; Node next; } public LinkList() { head = new Node(); head.next = null; tail = new Node<E>(); } public void insert(E e, int index) { Node newNode = new Node<E>(); newNode.data = e; Node before = head; Node temp = head.next; while (index >= 0) { if (index == 0) { before.next = newNode; newNode.next = temp; size++; break; } before = temp; temp = temp.next; index--; } } public void add(E e) { Node node = new Node(); node.data = e; node.next = null; if (head.next == null) { head.next = node; } tail.next = node; tail = node; size++; } public E get(int index) { if (index > size - 1) { return null; } Node temp = head.next; while (index >= 0) { if (index == 0) { return (E) temp.data; } temp = temp.next; index--; } return null; } public E getFirst() { return get(0); } public E getLast() { return get(size - 1); } public void remove(E e) { Node before = head; Node temp = head.next; while (temp != null) { if (temp.data.equals(e)) { before.next = temp.next; size--; break; } before = temp; temp = temp.next; } } @Override public String toString() { StringBuffer sb = new StringBuffer(); Node temp = head.next; while (temp != null) { sb.append(temp.data + "->"); temp = temp.next; } return sb.toString(); } public int getLength() { return size; } }
相关推荐
alicelmx 2020-06-16
学习 2020-05-31
Cypress 2020-03-01
niushao 2020-01-19
xhao 2019-12-15
DemoQiao 2019-04-23
weiwolves 2018-09-10
mingyunxiaohai 2018-09-19
夏乐宾 2017-06-01
zhangxiafll 2012-02-02
kunfeifeifei 2018-04-12
广西信息安全学会 2018-12-19
thousfeet 2015-07-20
飞空静渡 2009-11-25
小金屋 2019-04-16
phptyong 2016-07-04
phpcrazy 2016-07-05
PHP100 2019-03-28