基础数据结构01:链表
来源:互联网 发布:三菱fx2n 4da编程实例 编辑:程序博客网 时间:2024/06/16 19:29
说明
链表的类似于一个连着一个的圆环。在链表中,要想访问某个节点,必须通过他的上一节点来访问。
Java实现
package com.algs.base;import java.util.Iterator;import java.util.NoSuchElementException;public class Link<Item> implements Iterable<Item> { private Node first = null; // 链表的第一个元素 private int n = 0; // 链表的长度 private class Node{ private Item item; // 链表节点的值 private Node next; // 指向下一节点 public String toString(){ return (String) this.item; } } // 向链表中添加数据 public void add(Item item){ Node oldFirst = first; first = new Node(); first.item = item; first.next = oldFirst; n++; } // 翻转链表 public void reverse(){ Node next = first.next; first.next = null; // 避免遍历时死循环 while(next!=null){ Node temp = next.next; next.next = first; first = next; next = temp; } } public int size(){ return n; } @Override public Iterator<Item> iterator() { return new ListIterator(); } //链表遍历实现 private class ListIterator implements Iterator<Item> { private Node current = first; public boolean hasNext() { return current != null; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } } public static void main(String[] args) { Link<String> link = new Link<String>(); link.add("one"); link.add("two"); link.add("three"); for(String node:link){ //打印结果为three->two->one-> System.out.print(node+"->"); } //翻转链表 System.out.println(""); link.reverse(); for(String node:link){ //打印结果为one->two->three-> System.out.print(node+"->"); } }}
下一篇:基础数据结构02:队列
阅读全文
0 0
- 基础数据结构01:链表
- 数据结构基础:链表
- 基础数据结构 - 链表
- [数据结构基础] 链表
- 数据结构基础算法-链表
- 数据结构基础【01】基本概念
- 数据结构与算法-基础数据结构(链表)
- 基础数据结构 链表、栈、队列
- 数据结构基础
- 数据结构基础
- 数据结构基础
- 数据结构基础
- 数据结构基础
- 基础数据结构
- 数据结构基础
- 数据结构基础
- 数据结构基础
- 数据结构基础
- java 基础-集合
- 0023_Merge k Sorted Lists
- 关于MVC和DAO设计模式
- 【死磕Java并发】-----J.U.C之ConcurrentHashMap红黑树转换分析
- Isolation Forest算法实现详解
- 基础数据结构01:链表
- LeetCode 1,11,26
- No implementation found for native ...Android JNI问题
- js中关于return返回值的用法
- RedHat下防火墙配置
- 快速算法入门——基于《算法》3-sum找出所有和为0的三元整数组
- CAS原子操作实现无锁及性能分析
- 关于在web中的数据传递
- 你真的会使用google搜索?