数据结构与算法_链表_单向链表_JAVA实现

单向链表JAVA实现,包括头插法与尾插法 2020.03.24

class Node{
	public String contextString = null;
	public Node next= null;
	
	public Node(String contextString) {
		this.contextString = contextString;
	}
}
class LinkedList {
	Node rootNode = null;
	
	//尾插法
	public boolean insert(Node newNode) {
		if(rootNode == null) {
			rootNode = newNode; 
			return true;
		}
		Node currentNode  = rootNode;
		Node parentNode = null;
		while(currentNode != null) {
			parentNode = currentNode;
			currentNode = currentNode.next;
		}
		parentNode.next = newNode;
		return true;
	}
	
	//头插法
	public boolean insert2(Node newNode) {
		if(rootNode == null) {
			rootNode = newNode; 
			return true;
		}
		newNode.next = rootNode; 
		rootNode = newNode;
		return true;
	}
	
	public void order() {
		Node currentNode  = rootNode;
		while(currentNode != null) {
			System.out.println("\t" + currentNode.contextString);
			currentNode = currentNode.next;			
		}
	}
	
	public boolean delete(String deleteContext) {
		Node currentNode  = rootNode;
		Node parentNode = null;
		if(rootNode.contextString.equals(deleteContext)) {
			rootNode = null;
			return true;
		}
		while(currentNode != null) {
			if(currentNode.contextString.equals(deleteContext)) {
				parentNode.next = currentNode.next;
				return true;
			}
			parentNode = currentNode;
			currentNode = currentNode.next;
		}
		return false;
	}
}
public class Linked {
	public static void main(String[] args) {
		LinkedList linkedList = new LinkedList();
		linkedList.insert(new Node("a"));
		linkedList.insert(new Node("b"));
		linkedList.insert(new Node("c"));
		linkedList.insert(new Node("d"));
		linkedList.insert(new Node("e"));
		linkedList.order();
		linkedList.delete("d");
		linkedList.order();
		LinkedList linkedList2 = new LinkedList();
		linkedList2.insert2(new Node("A"));
		linkedList2.insert2(new Node("B"));
		linkedList2.insert2(new Node("C"));
		linkedList2.insert2(new Node("D"));
		linkedList2.insert2(new Node("F"));
		linkedList2.order();
		linkedList2.delete("D");
		linkedList2.order();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值