LinkList其实没那么难
来源:互联网 发布:大卫泰勒增高 知乎 编辑:程序博客网 时间:2024/04/29 07:35
虽然理论上对链表的理解很到位,但是从代码实现上每次都无从下手。
链表是由一个个结点组成 定义一个结点类
package com.Techck.Linklist;
/**
* 链表节点对象
* @author Administrator
*
*/
public class Node {
/**
* 数据域属性
*/
private String date;
/**
* 下一个引用域属性
*/
private Node next;
/**
* 构造函数,根据节点数据和下一个节点的引用
* @param date 数据
* @param next 下一个节点的引用
*/
public Node(String date, Node next) {
super();
this.date = date;
this.next = next;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}
然后就是定义一个链表类,这里我是为了方便,写了一个链表接口,然后去链表类去实现它
package com.Techck.Linklist;
public class LinkList implements LinkListInterface {
/**
* 定义头节点
*/
public Node head;
@Override
public int size() {
int count = 0;
// 判断当前首节点是否为空
if (head == null) {
return count;
} else {
// 如果头节点存在,则累加一次计数器
count++;
// 获取下一个节点
Node node = head.getNext();
while (node != null) {
count++;
node = node.getNext();
}
}
return count;
}
@Override
public Node get(int index) {
// 拿到指定索引位置的节点对象
if (index < 0) {
// 如果索引位置为负数,打印异常栈
try {
throw new Exception("索引不能为负数:" + index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
int count = 0;
// 如果index为0的情况,则直接返回头节点
if (count == index) {
return head;
}
// 判断索引是不是已经越界
if (index < size()) {
// 如果没有越界的情况,获取头节点的下一个节点
Node node = head.getNext();
while (node != null) {
count++;
if (count == index) {
return node;
}
node = node.getNext();
}
} else {
// 如果索引位置为负数,打印异常栈
try {
throw new Exception("索引越界");
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
public void add(String value) {
// 链表添加节点
// 创建一个新的节点
Node node = new Node(value, null);
if (size() == 0) {
head = node;
} else {
Node node1 = get(size() - 1);
node1.setNext(node);
}
}
@Override
public void add(String value, int index) {
// 链表添加节点
// 创建一个新的节点
Node node = new Node(value, null);
if(head==null){
head=node;
return;
}
//先拿到当前索引位置的节点
if(index==0){
node.setNext(head);
head = node;
return;
}
Node node_current = get(index);
Node node_parent = get(index-1);
node_parent.setNext(node);
node.setNext(node_current);
}
@Override
public void remove(int index) {
// TODO Auto-generated method stub
}
}
链表里提供各种对链表操作的方法,链表其实就是那么简单
- LinkList其实没那么难
- 其实没那么难
- 其实没那么难
- android中微信支付!! 其实没那么难
- 设计师自学其实也没那么难
- 机器学习,其实没那么难~
- 其实生活没那么糟
- 创新,其实没那么玄
- 其实你没那么好
- java基础----java其实没那么难(基础很重要)
- 学习Python到写poc其实没那么难
- REACT NATIVE 真正的路线,其实没那么难
- 其实爱不爱没那么重要
- 快排其实没那么快
- 其实他没那么喜欢你
- 其实他没那么喜欢你
- 《他其实没那么喜欢你》经典台词
- 自己画View其实没那么可怕
- Listener监听器 静态注册--杂记
- android学习笔记记录
- 数字音乐洗牌,网易云音乐版权之痛
- 判断一个整数是否为回文数
- Leetcode: Fraction to Recurring Decimal
- LinkList其实没那么难
- MongoDB vs TokuMX 性能测试
- MongoDB V3 & V2 版本锁性能对比测试及锁的基本概况
- TCP/IP、Http、Socket的区别
- Need to specify class name in environment or system property, or as an applet parameter, or in an ap
- Iphone 上字体大全
- 软件包javax.servlet不存在的解决办法
- hdu 1717 小数化分数2
- PHP文件上传示例