数据结构之单向链表(java实现)
2015-09-09 00:48
726 查看
单向链表是一种十分基础的数据结构,是线性表的一种,为了更清楚一点,今天使用java将其实现,实现过程如下
定义节点
/* * 节点类 * */ public class Node { Object data;//存储节点数据 Node next;//指向下一节点 }
定义操作
public interface LinKed { public Node get(int p); public void Insert(int p, Object data); public void delete(int p); public void clean(); public int size(); }
实现单向链表
public class SingleLinked implements LinKed { private Node head;// 头节点 private int length;// 链表长度 /* * 初始化链表 */ public SingleLinked() { head = null; length = 0; } /* * 清空链表 */ public void clean() { head = null; length = 0; } /* * 获取链表第p个节点 */ public Node get(int p) { Node current = head; if (p > 0 && p <= length) { for (int i = 0; i < p - 1; i++) { current = current.next; } return current; } return null; } /* * 插入节点头插法 */ public void headInsert(Object data) { Node n = new Node(); n.data = data; n.next = head; head = n; length++; } /* * 插入节点在p节点 */ public void Insert(int p, Object data) { Node current = head; Node n = new Node(); n.data = data; if (p > 0 && p <= length + 1) { for (int i = 0; i < p - 2; i++) { current = current.next; } n.next = current.next; current.next = n; length++; } } /* * 删除第p个节点 */ public void delete(int p) { Node current = head; // 遍历链表直到p节点的前一节点 if (p > 0 && p <= length) { if (p == 1) {// 若删除的是头节点 head = current.next; length--; return; } else { for (int i = 1; i <= p; i++) { if (i == p - 1) { current.next = current.next.next; length--; } else { current = current.next; } } } } } /* * 打印链表 */ public void print() { Node current = head; for (int i = 0; i < length; i++) { System.out.print(current.data + "-->"); current = current.next; } System.out.println(); } @Override public int size() { return this.length; } }
测试
public class Test { public static void main(String[] args) { SingleLinked sl = new SingleLinked(); sl.headInsert("a1"); sl.headInsert("a2"); sl.headInsert("a3"); sl.headInsert("a4"); sl.print(); sl.delete(4); sl.print(); System.out.println(sl.get(3).data); sl.Insert(4, "a5"); sl.print(); sl.Insert(2, "a6"); sl.print(); } }
相关文章推荐
- 数据结构Java实现07----队列:顺序队列&顺序循环队列、链式队列、顺序优先队列
- 数据结构之队列
- java数据结构与算法值优先级队列
- 数据结构---线性顺序表操作(c++)
- 数据结构——二叉树的层次遍历
- 数据结构学习之路-第三章:栈的应用
- 数据结构面试题1.2.2-下排每个数都是先前上排那十个数在下排出现的次数
- 数据结构之线性表的顺序结构操作2-(删除,插入,查值等)
- 数据结构之---C语言实现快速排序(多个版本)
- 数据结构——有序线性表的的插入与删除
- 数据结构学习之 union 共用体(union 到底有什么用?)
- 浅谈数据结构-顺序表查找
- 20150908数据结构(C语言版)算法时间复杂度问题
- 数据结构之栈
- 数据结构之---C语言实现归并排序
- 数据结构之---C语言实现堆排序
- 数据结构面试题1.2.1-把二元查找树转变成排序的双向链表
- 数据结构之单向链表操作1-(插入,删除,交换,反转,排序等操作)
- 浅谈数据结构-查找
- 数据结构之---C语言实现希尔排序