JAVA实现单链表
2017-11-30 20:07
357 查看
节点
package com.ghg.data_structure.sit; /** * 节点 * @author Administrator * */ public class Node { /** * 数据 */ public int data; /** * 下一个元素 */ public Node next; public Node(int data, Node next) { super(); this.data = data; this.next = next; } }
链表
package com.ghg.data_structure.sit; import com.ghg.data_structure.singlinktab.Node; import sun.reflect.generics.tree.VoidDescriptor; public class LinkList { public Node first; public LinkList() { this. first = null; } /** * 添加元素到第个位置 * @param node */ public void addFirst(Node node){ node.next=first; first=node; } /** * 删除第一个元素 */ public void deleteFirst(){ first=first.next; } public void addNode(Node node){ //一个指针 Node current =first; /** * 找到最后个元素 */ while(current.next!=null){ current=current.next; } //添加到最后 current.next=node; } /** * 插入指定位置 * @param index * @param node */ public void addNodeByIndex(int index,Node node){ if(index<1 || index >length()+1){ System.out.println(index+ " 位置不正确 length "+length()); return; } /* * 记录我们遍历到第几个结点了,也就是记录位置 要把index添加到length后面 */ int length=1; /** * 指针 */ Node current=first; while(current.next!=null){ /** * 判断是否到达指定位置。 */ if(index==length++){ //插入操作。 把原来的下一个赋值给新的节点 node.next=current.next; current.next=node; return; } current=current.next; } } /** * 删除节点 */ public void delNodeByIndex(int index){ if(index<1 || index >length()+1){ System.out.println(index+ " 位置不正确 length "+length()); return; } /* * 记录我们遍历到第几个结点了,也就是记录位置 要把index添加到length后面 */ int length=1; /** * 指针 */ Node current=first; while(current.next!=null){ if(index==length++){ /** * 当前=下一个一下一个 */ current.next=current.next.next; return; } current=current.next; } } /** * 获取链表的长度 */ public int length(){ int length=1; Node current =first; /** * 找到最后个元素 */ while(current.next!=null){ length++; current=current.next; } return length; } /** * 显示 */ public void display(){ Node current = first; while (current != null) { current.display(); current = current. next; } System. out.println(); } }
相关文章推荐
- java实现单链表
- 数据结构的Java实现——单链表
- java单链表实现一元多项式加法和乘法运算
- 算法:java 实现单链表的反转
- 单链表与双向链表的Java实现
- java实现单链表
- 用java实现单链表
- 线性表java实现之单链表存储源码
- Java实现单链表的逆转置
- 用java简单的实现单链表的基本操作
- (Java)单链表Java语言链式结构实现(数据结构四)
- (Java)单链表Java语言链式结构实现(数据结构四)
- 单链表操作java实现
- Java中的链表以及单链表的实现
- java实现单链表的初始化,创建,删除,插入,查找,排序,同项删除,退出等功能
- (Java)单链表Java语言顺序结构实现(数据结构三)
- Java实现单链表
- java实现双向循环链表和单链表
- java 基于单链表的实现的栈
- Java单链表的实现