单向链表代码及原理解析

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 著    周详 译

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值