尾插法实现LinkedList
来源:互联网 发布:机械行业推广优化方案 编辑:程序博客网 时间:2024/06/02 00:37
本科时学习数据结构一直是使用c语言,最近想到使用java实现尾插法链表会是什么样的效果呢,于是编写了一个简单的尾插法LinkedList,实现了迭代器,增加,删除,插入。供参考:
import java.util.Iterator;/** * Created by wzy on 17-2-24. */public class MyLinkedList<T> implements Iterable<T>{ public static class Node<U>{ U item; Node<U> next; public Node(){ item = null; next = null; } public Node(U item, Node<U> next){ this.item = item; this.next = next; } } private Node<T> top = new Node<T>(); private Node<T> node = top; public void add(T item){ node.next = new Node<T>(item, null); node = node.next; } public void insert(int index, T item){ int i = -1; Node<T> pre = null; Node<T> now = null; now = top; while(i < index){ pre = now; now = now.next; i++; if (i > index && now == null){ throw new RuntimeException("index error"); } } pre.next = new Node<T>(item, now); } public void remove(int index){ int i = -1; Node<T> pre = null; Node<T> now = null; now = top; while(i < index){ pre = now; now = now.next; i++; if (i > index && now == null){ throw new RuntimeException("index error"); } } pre.next = now.next; } @Override public Iterator<T> iterator() { return new Iterator<T>() { Node<T> now = top; @Override public boolean hasNext() { return now.next != null; } @Override public T next() { now = now.next; return now.item; } }; } @Override public String toString() { StringBuffer stringBuffer = new StringBuffer("{"); node = top.next; while(node != null){ stringBuffer.append(node.item + ", "); node = node.next; } stringBuffer.delete(stringBuffer.length() -2 , stringBuffer.length()); stringBuffer.append("}"); return stringBuffer.toString(); } public static void main(String[] args) { MyLinkedList<String> list = new MyLinkedList<>(); list.add("1"); list.add("2"); list.add("3"); System.out.println(list); list.insert(1, "4"); list.insert(4, "5"); System.out.println(list); list.remove(4); System.out.println(list); for (String s : list){ System.out.println(s); } }/*output:{1, 2, 3}{1, 4, 2, 3, 5}{1, 4, 2, 3}1423*/}
0 0
- 尾插法实现LinkedList
- LinkedList实现
- LinkedList实现
- LinkedList实现
- LinkedList实现
- 实现LinkedList
- LinkedList实现
- LinkedList实现
- LinkedList实现
- 用LinkedList实现栈
- 用LinkedList实现队列
- 使用LinkedList实现Queue
- 类实现之LinkedList
- 通过LinkedList实现队列
- LinkedList实现栈,队列
- ArrayList和LinkedList实现
- Linkedlist实现Queue
- 自定义LinkedList实现
- 1020. 月饼 (25)
- Android Studio安装及配置过程
- Android自定义View(十一)_Path之玩出花样(PathMeasure)
- MySQL数据库优化的八种方式
- 数组
- 尾插法实现LinkedList
- SSH的基本概念
- live555 fNumTruncatedBytes〉0
- 17.2.24 caffe中solver层的参数概述
- 最简单的TTcpServer与TTcpClient通信实例-Delphi
- 国际最新消息:Google 宣布成功攻破 SHA-1 加密
- android developer tiny share-20170217
- OkhttpUtils的Cookie存储问题
- 文章标题