链表的实现(Java)
2016-09-27 23:49
330 查看
链表是一种基本的数据结构,与数组相比链表存储数据更为灵活。在本实例中,实现的是链表结构,使用Java语言实现。 链表类的设计,链表由链节点构成,每个链节点分别由数据域(value)和节点域(next)组成,数据域用于存储数据,节点域用于指向下一个节点。
class Node{ int value;//数据域 Node next;//节点域 public Node(int data){ this.value=data;//节点类构造函数 } } public class LinklistNode { Node node;//节点 public LinklistNode(){ this.node=null;//链表构造函数 } public Node initLinklist(int data){ Node temp; temp=new Node(data); temp.next=this.node; this.node=temp; return this.node; }//初始化链表,建立头结点 public void addNode(int data){ Node temp; temp=new Node(data); temp.next=this.node; this.node=temp; temp=null; }//增添数据,使用从链表头部进行插入 public int selectNode(int pos){ Node current; int p=0; current=this.node; while(p<=pos-1&¤t!=null){ current=current.next; p++; } return current.value; }//根据输入位置返回指定位置的数据值 public int deleteNode(){ Node temp; temp=this.node; this.node=temp.next; return temp.value; }//删除节点 public void printLinklistNode(){ Node current; current=this.node; while(current!=null){ System.out.print(current.value+" "); current=current.next; }//输出链表数据 } }
测试主函数代码
public class testLinklist { public static void main(String[] args) { // TODO Auto-generated method stub LinklistNode head=null; head=new LinklistNode(); head.initLinklist(5);//生成头结点 for(int i=0;i<5;i++){ head.addNode(i);//添加节点 } head.printLinklistNode();//输出链表 System.out.println(); head.deleteNode();//删除链表节点 head.printLinklistNode(); System.out.println(); head.deleteNode(); head.printLinklistNode(); System.out.println(); System.out.println("pos 2 value:"+head.selectNode(2));//输出指定位置的节点数据值 } }
测试效果图示:
相关文章推荐
- 使用JAVA实现双向链表
- JAVA实现双向链表
- 利用链表实现队列的Java代码
- Java实现链表
- Java实现链表
- Java语言中链表和双向链表的实现
- Java数据结构之简单链表的定义与实现方法示例
- JAVA实现链表
- java 单向链表的实现
- java链表实现约瑟夫算法
- Java 实现 链表
- Java语言中链表和双向链表的实现
- JAVA 语言中链表和双向链表的实现
- 某一天的思考题(使用Java实现链表)的参考答案
- JAVA实现双向链表
- java 语言中链表和双向链表的实现!
- Java语言中链表和双向链表的实现-Java基础-Java-编程开发
- Java 用单链表实现多项式加减乘
- 用java数组实现基本链表和可自扩充的链表
- Java数据结构之双端链表原理与实现方法