java实现单链表的基本操作
来源:互联网 发布:概率图模型 知乎 编辑:程序博客网 时间:2024/05/17 23:15
package link;/** * 单链表模型:实现插入、删除、查找、反转、输出等操作 * @author USER * *///结点类class Node{protected int data; //结点数据protected Node next;//结点指针//结点构造方法public Node(int data) {this.data=data;}public void print() {System.out.print(data+" ");}}//链表类class Link{public Node head;//头结点private int pos = 0;//结点位置public Link(){this.head = null;}//插入一个头结点public void addHeadNode(int data) {Node node = new Node(data);node.next = head;//此处head为nullhead = node;//此处head为新加入的结点}//在任意位置index处插入一个结点,插入结点在index之后的那个结点public void add(int index, int data) {Node node = new Node(data);Node previous = head;Node current = head;while (pos!=index) {previous = current;current = current.next;pos++;}node.next = current;previous.next = node;pos = 0;}//在任意位置index处删除一个结点,删除的是第index个结点,不能删除第一个结点public void delete(int index) {Node previous = head;Node current = head;pos++;while (pos!=index) {previous = current;current = current.next;pos++;}previous.next = current.next;pos = 0;}//删除头结点public void deleteHead() {Node temp = head;head = temp.next;}//根据结点位置查找结点信息,注意:index是指第几个位置,pos是从0开始代表第一个位置public Node findByPos(int index) {Node current = head;pos++;while (pos != index) {current = current.next;pos++;}pos = 0;return current;}//根据结点数据查找结点信息public Node findByData(int data) {Node current = head;while (current.data != data) {if (current.next == null) {return null;}else {current = current.next;}}return current;}//整个链表的长度public int length() {int size = 0;Node current = head;while (current != null) {current = current.next;size++;}return size;}//显示整个链表public void show() {Node current = head;while (current != null) {current.print();current = current.next;}System.out.println();}}public class MySingleLinkList {public static void main(String[] args) {Link list = new Link();list.addHeadNode(10);list.show();//10list.add(1, 12);list.add(2, 13);list.add(3, 14);list.add(4, 15);list.add(5, 16);list.show();//10 12 13 14 15 16System.out.println(list.length());//6list.delete(2);list.show();//10 13 14 15 16list.delete(2);list.show();//10 14 15 16System.out.println(list.length());//4list.deleteHead();list.show();//14 15 16System.out.println(list.findByPos(2).data);//15System.out.println(list.findByPos(3).data);//16System.out.println(list.findByData(15).data);//15}}
0 0
- java实现单链表的基本操作
- java实现单链表的基本操作
- java自己实现单链表的基本操作
- 单链表基本操作java实现
- Java实现单链表基本操作
- 用java简单的实现单链表的基本操作
- 用java简单的实现单链表的基本操作
- 用java简单的实现单链表的基本操作
- 单链表的基本操作与算法(Java实现)
- 带头节点的单链表及其基本操作(Java实现)
- 单链表的基本操作实现
- 单链表基本操作的实现
- 单链表的基本操作实现
- 单链表的基本操作实现
- 单链表的基本操作实现
- Java实现二叉树的基本操作
- Java实现二叉树的基本操作
- 堆的基本操作集【Java实现】
- [网络子系统] Netfilter机制分析
- 素材网
- 项目总算完工了
- 笔试面试(3)阿里巴巴2014笔试题详解(9月22北京)
- 命令别名与历史命令
- java实现单链表的基本操作
- Eclipse无法自动补全代码的解决办法
- Atlantis(扫描线+线段树+离散化)
- Java中的内存模型和多线程分析
- Cocos2d-x读取本地文件
- UVa1218 Perfect Service
- 关于正则表达式
- The Balance(扩展欧几里得算法)
- 每天一点android开发---------ContentProvider