1.单向链表java代码实现
1、定义节点类IntSLLNode
public class IntSLLNode{
//info域用来存储信息
public int info;
//next域用来把节点链在一起形成链表
public IntSLLNode next;
public IntSLLNode(int i){
this(i,null);//和IntSLLNode(i,null)含义相同
}
public IntSLLNode(int i,IntSLLNode n){
info = i;
next=n;
}
}
2、创建单向链表
public class IntSLList{
//定义head和tail域分别指向第一个和最后一个节点
protected IntSLLNode head,tail;
public IntSLList(){
head = tail =null;
}
public boolean isEmpty(){
return head == null;
}
//在链表表头增加一个节点
public void addToHead(int el){
head = new IntSLLNode(el,head);
if(tail == null)
tail = head;
}
//在链表表尾增加一个节点
public void addToTail(int el){
if(!isEmpty()){
tail.next = new IntSLLNode(el);
tail = tail.next;
}
else head = tail = new IntSLLNode(el);
}
//删除头节点并返回节点的info域
public int deleteFromHead(){
int el = head.info;
if(head == tail)
head = tail = null;
else head =head.next;
return el;
}
//删除尾节点并返回节点的info域
public int deleteFromTail(){
int el = tail.info;
if(head == tail)
head = tail = null;
else {
IntSLLNode tmp;
for(tmp = head;tmp.next != tail;tmp = tmp.next);
tail = tmp;
tail.next =null;
}
return el;
}
//打印所有节点的info域
public void printAll(){
for(IntSLLNode tmp = head; tmp !=null; tmp = tmp.next)
System.out.println(tmp.info + " ");
}
//查找info域
public boolean isInList(int el){
IntSLLNode tmp;
for(tmp = head;tmp!=null&&tmp.info!=el;tmp=tmp.next);
return tmp!=null;
}
//按照info域删除节点
public void delete(int el){
if(!isEmpty())
if(head == tail&&el == head.info)
head = tail = null;
else if(el == head.info)
head=head.next;
else {
IntSLLNode pred,tmp;
for(pred = head,tmp = head.next;tmp !=null&&tmp.info!=el;pred = pred.next,tmp = tmp.next);
if(tmp !=null){
pred.next = tmp.next;
if(tmp == tail)
tail = pred;
}
}
}
}
3、创建test类检测代码
public class test {
public static void main(String[] args) {
}
}
2.代码解析
1.创建节点head,tail并初始化为null
protected IntSLLNode head,tail;
public IntSLList(){
head = tail =null;
}
2.在链表表头增加新节点
public void addToHead(int el){
head = new IntSLLNode(el,head);
if(tail == null)
tail = head;
}
#其它的操作都是类似的,在这里就不重复造轮子了
3.时间复杂度
4.总结
1、调用构造函数IntSLLNode(int el,IntSLLNode n)时,第一个参数是值传递,第二个参数是引用传递
#参考书籍
数据结构与算法java语言版(第二版) Adam Drozdek 著 周详 译