2. Implementation of linked list: with sentinel

1. Definition of singly linked list with sentinel

/**
 * 单向链表----带哨兵
 */
public class SinglyLinked {

	/**
	 * 节点类
	 * 数据域和地址域
	 */
	private static class Node {
		int value; //值
		Node next; // 指向下一个节点

		public Node() {

		}

		public Node(int value, Node next) {
			this.value = value;
			this.next = next;
		}

	}

	/**
	 * 1.头指针
	 */
	private Node head = new Node(0, null);

}

2. Add elements to the end of the linked list, first find the last node, and then insert

	public Node findLast() {
		Node p = head;
		while (p.next != null) {
			p = p.next;
		}
		return p;
	}

 

public void addLast(int value) {
		Node last = findLast();
		last.next = new Node(value, null);
	}

3. Find the node according to the index, the condition is to always find the last empty p!=null

	private Node findNode(int index) {
		int i = -1;
		for (Node p = head; p != null; p = p.next, i++) {
			if (i == index) {
				return p;
			}
		}
		return null; // 没找到
	}

The serial number of the head node is -1, so i=-1 starts 

	public void get(int index) {
		Node node = findNode(index);
		if (node == null) {
			System.out.println("没找到");
			return;
		}
		System.out.println(node.value);
	}

4. Insert a value at the index position index

First find the node of index-1, and then insert it later, let the new node connect first.

	public void insert(int index, int value) {
		Node p = findNode(index - 1);
		if (p == null) {
			System.out.println("插入失败");
			return;
		}
		// 插入节点
		p.next = new Node(value, p.next);
	}

5. Add a node to the head of the linked list

Directly call the index() method, the insertion index position is 0

	public void addFirst(int value) {
		insert(0, value);
	}

6. Delete according to the index position

	public void remove(int index) {
		Node pre = findNode(index - 1);
		if (pre == null) {
			System.out.println("删除失败");
			return;
		}
		// 指向删除节点
		Node removed = pre.next;
		if (removed == null) {
			System.out.println("删除失败");
			return;
		}
		pre.next = removed.next;
	}

7. traverse 

The condition is p!=null, all nodes are read

	public void loop() {
		Node p = head.next;
		while (p != null) {
			System.out.println(p.value);
			p = p.next;
		}
	}

Guess you like

Origin blog.csdn.net/jbkjhji/article/details/131216786