1 Star 0 Fork 1

黎明与雪/MyList

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
MyList.java 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
黎明与雪 提交于 2017-12-14 13:47 . 一些单向列表方法
package teach.test;
public class MyList {
public static class Node{
Object data;
Node next;
public Node(Object data){
super();
this.data = data;
next = null;
}
}
Node head;
public MyList(){
head = null;
}
//清空链表
public void clear(){
head = null;
}
//遍历打印链表
public void travel(){
Node p = head;
while(p != null){
System.out.println(p.data);
p = p.next;
}
}
//判断链表是否为null
public boolean isEmpty(){
return head == null;
}
public int size(){
Node p = head;
int sum = 0;
while(p != null){
sum ++;
p = p.next;
}
return sum;
}
public void insert(Object obj, int pos){
if(pos < 0 || pos > size()){
throw new RuntimeException("插入的"+ pos +"越界了!");
}
Node newNode = new Node(obj);
if(pos == 0){
newNode.next = head;
head = newNode;
}
if(pos >= size()-1){
get(size()-1).next = newNode;
}else{
newNode.next = get(pos);
get(pos - 1).next = newNode;
}
}
/**
* 获得特定位置的节点
* @param post
* @return
*/
public Node get(Integer pos){
if(pos < 0 || pos > size()){
throw new RuntimeException("传入的"+ pos +"越界了!");
}
//获取头部节点
if(pos == 0){
return head;
}
Node p = head;
for(int i = 0; i < pos; i++){
p = p.next;
}
return p;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/fangzhiyong/MyList.git
git@gitee.com:fangzhiyong/MyList.git
fangzhiyong
MyList
MyList
master

搜索帮助