package cn.ahjz.datastructure;
/**
* 模拟单链表 节点定义
*
* @author cs
*
*/
public class ListNode {
Object data; // 数据域
ListNode next;// 指针域
public ListNode() {
}
public ListNode(Object data, ListNode next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
@Override
public String toString() {
return "ListNode [data=" + data + ", next=" + next + "]";
}
}
package cn.ahjz.datastructure;
/**
* 模拟单链表基本操作
*
* @author cs
*
*/
public class SingelList {
ListNode head = new ListNode();// 头结点 不保存数据
private int size;// 链表长度
/**
* 判断链表是否为空
*
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 按顺序添加数据
*
* @param data
* 数据
*/
public void add(Object data) {
// // 创建新节点加入
// ListNode node = new ListNode();
// // 数据域赋值
// node.data = data;
// // System.out.println(size);
// // 添加到链表中
// getData(size - 1).next = node;
//
// // 链表长度加1
// size++;
this.add(size, data);;
}
/**
* 指定位置添加数据
*
* @param index
* 位置索引
* @param data
* 数据
*/
public void add(int index, Object data) {
//创建加入的节点
ListNode node = new ListNode();
node.data = data;
//遍历到指定位置节点
ListNode p = getData(index-1);
//指定位置添加节点
node.next = p.next;
p.next = node;
size++;
}
/**
* 判断时候索引越界
*
* @param index
* 索引位置
* @return
*/
public boolean isFull(int index) {
return size - 1 < index;
}
/**
* 返回链表长度
*
* @return
*/
public int length() {
return size;
}
/**
* 获取指定位置节点
*
* @param index
* 索引位置
* @return
*/
public ListNode getData(int index) {
// 初始遍历指针指向头结点
ListNode node = head;
// 遍历链表
for (int i = 0; i <= index; i++) {
node = node.next;
}
return node;
}
}