数据结构1 -- 链表的基本方法实现

package NodeList;

public class NodeList {
	static Node head;// 头结点 作为链表中第一个节点
	static Node end;// 尾结点 作为链表中最后一个节点

	public static void main(String[] args) {

		head = new Node(0);
		end = head;
		addNodeBeforeList(new Node(-1));
		addNodeBeforeList(new Node(-2));
		addNodeAfterList(new Node(1));
		addNodeAfterList(new Node(2));

		showList();
		System.out.println("List length is:" + getListLength());

		deleteNode(0);
		showList();
		System.out.println("List length is:" + getListLength());
	}

	// 在链表头部插入节点
	public static void addNodeBeforeList(Node n) {
		// 先将带插入节点的next设为当前head
		n.next = head;
		// 再将带插入节点设为head
		head = n;
	}

	// 在链表尾部插入节点
	public static void addNodeAfterList(Node n) {
		// 先将end的next设为n
		end.next = n;
		// 再将带插入节点n设为end
		end = n;
	}

	// 从链表头部删除节点
	public static void deleteNodeBeforeList() {

		head = head.next;

	}

	// 删除链表中包含指定元素的节点
	public static void deleteNode(int num) {
		Node current_node = head;
		// 判断是否是头结点
		if (current_node.data == num)
			head = null;

		boolean exist = false;

		while (current_node.next!= null) {
			// 先找到包含num元素节点的前一个节点
			if ((current_node.next).data == num) {
				exist = true;
				// 如果是尾节点是包含num的节点
				if ((current_node.next).next == null) {
					// 设当前节点为尾节点
					current_node.next = null;
				} else {
					current_node.next = current_node.next.next;

				}

			}

			current_node = current_node.next;
		}

		if(!exist)
		{
			System.out.println("不存在");
			
		}
		
		
		
	}

	// 遍历节点
	public static void showList() {

		Node current_node = head;

		while (current_node != null) {
			System.out.println(current_node.data);
			current_node = current_node.next;

		}

	}

	// 获得链表长度
	public static int getListLength() {
		Node current_node = head;
		int len = 0;
		while (current_node != null) {
			len++;
			current_node = current_node.next;

		}
		return len;

	}

}

/*
 * 作为链表的基本节点类 两个成员变量 1. int data 节点中保存的数据 2. Node next 节点指向的下个节点
 */
class Node {
	int data;
	Node next;

	Node(int data) {
		this.data = data;
		next = null;
	}

	void setdata(int data) {
		this.data = data;
	}

	void setNext(Node n) {
		this.next = n;
	}

	int getdata() {

		return data;
	}

	Node getNext()

	{

		return next;

	}

}

  结果:

-2
-1
0
1
2
List length is:5
-2
-1
1
2
List length is:4
原文地址:https://www.cnblogs.com/xiaodeyao/p/5301837.html