java单向链表的创建和使用

public class test {
public static  void main(String[] args) {
	Link l = new Link();
	Node n1 = new Node(1,null);
	Node n2 = new Node(2,null);
	Node n3 = new Node(3,null);
	Node n4 = new Node(4,null);
	l.add(n1);
	l.add(n2);
	l.add(n3);
	l.add(n4);
	System.out.println(l.count());
	l.print();
	try {
		//删去第三个元素
		l.remove(3);
		l.print();
		System.out.println("=====");
	} catch (MyException e) {
		e.printStackTrace();
	}
}
}

public class Node {
	Object element;
	Node next;
	public Node() {}
	public Node(Object element,Node next) {
		this.element = element;
		this.next = next;
	}

}

public class Link {
Node header = null;
static int len = 0;
//增加节点
public void add(Node n) {
	if(header == null) {
		header = n;
	}else {
		Node currentLast = findLast(header);
		currentLast.next = n;
	}
}
private Node findLast(Node n) {
	if(n.next == null) {
		return n;
	}
	return findLast(n.next);
}
public int count() {
	Node n = header;
	while(n != null) {
		len = len + 1;
		n = n.next;
	}
	return len;
}
//删去第k个节点
public void remove(int k) throws MyException  {
	
	  if(header == null) { throw new MyException("头指针为空,不能删去节点"); }else {
	 
		
		Node currentSecondLast = research(k - 1);
		//System.out.println("currentSecondLast.element"+currentSecondLast.element);
		Node removeNode = research(k);
		System.out.println("removeNode.element"+removeNode.element);
		if(removeNode.next!=null) {
		currentSecondLast.next =research(k+1);
		//System.out.println("currentSecondLast.next.element" + currentSecondLast.next.element);
		removeNode.next = null;
		}else {
			currentSecondLast.next = null;
		}
	}
}
//查找第i个节点(从1开始)
private Node research(int i) {
	Node n = header;
	if(i == 1) {
		return n;
	}else{
		for(int j = 2;j<i + 1;j++) {
			n = n.next;
		}
		return n;
	}
	}
	

public void print() {
	Node temp = header;
	while(temp != null) {
		System.out.print(temp.element + " ");
		temp = temp.next;
	}
	System.out.println();
}
}

public class MyException extends Exception{
	public MyException() {}
	public MyException(String s) {
		super(s);}
}
``

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值