数据结构-单向链表

package com.mzs.demo5;

public class Node {
	
	private int data;
	private Node next;
	
	public Node(int data) {
		this.data = data;
	}
	
	public void setData(int data) {
		this.data = data;
	}
	
	public void setNext(Node next) {
		this.next = next;
	}
	
	public int getData() {
		return this.data;
	}
	
	public Node getNext() {
		return this.next;
	}
}

package com.mzs.demo5;

public class OneWayLinkedList {
	
	private static Node head = new Node(1);	// head node
	
	/**
	 * add new node (add at the end of the list)
	 * @param data the data value of new node
	 */
	public static void addNode(int data) {
		Node newNode = new Node(data);
		Node temp = head;
		while (temp.getNext() != null) {
			temp = temp.getNext();
		}
		temp.setNext(newNode);
		/** add at the head of the list **/
		/*Node newNode = new Node(data);
		newNode.setNext(head);
		head = newNode;*/
	}
	
	/**
	 * give specified position and add a new node
	 * @param data the data value of the list
	 * @param position specified position
	 */
	public static void addNode0(int data, int position) {
		if (position == 0)
			addNode(data);
		if (position < 0 || position > length(head) - 1)
			throw new IllegalArgumentException("illegal argument");
		Node newNode = new Node(data);
		int length = 0;
		Node temp = head;
		while (temp.getNext() != null) {
			if ((length + 1) == position) {
				newNode.setNext(temp.getNext());
				temp.setNext(newNode);
				return ;
			}
			length++;
			temp = temp.getNext();
		}
	}
	
	/**
	 * delete the node of specified position
	 * @param position specified position
	 */
	public static void deleteNode(int position) {
		if (position < 1 || position > length(head) - 1) {
			throw new IllegalArgumentException("illegal argument");
		}
		Node temp = head;
		int length = 0;
		while (temp.getNext() != null) {
			if ((length + 1) == position) {
				Node deleteNode = temp.getNext();
				temp.setNext(deleteNode.getNext());
				return ;
			}
			length++;
			temp = temp.getNext();
		}
	}
	
	/**
	 * traversal the list
	 * @param head head node of the list
	 */
	public static void traversal(Node head) {
		Node temp = head;
		while (temp != null) {
			System.out.print(temp.getData() + " ");
			temp = temp.getNext();
		}
	}
	
	/**
	 * calculate the length of the list
	 * @param head
	 * @return the length of the list
	 */
	public static int length(Node head) {
		int length = 0;
		Node temp = head;
		if (head == null) 
			return 0;
		while (temp != null) {
			length++;
			temp = temp.getNext();
		}
		return length;
	}
	
	public static void main(String[] args) {
		addNode(2);
		addNode(3);
		addNode(4);
		deleteNode(1);
		//addNode0(0, 2);
		traversal(head);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_34561892/article/details/83544424