欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【java】【数据结构】java单链表 插入 删除 遍历

程序员文章站 2022-03-22 20:01:39
...
package wwr;

public class LinkedList<T> {
	
	//结点类
	public class Node {
		private T data;
		private Node next;
		public Node(T data, Node next) {
			this.data = data;
			this.next = next;
		}
		public Node(T data) {
			this(data, null);
		}
		public T getData() {
			return this.data;
		}
		public void setData(T data) {
			this.data = data;
		}
	}
	
	//成员变量
	private Node head;
	private int size;
	
	//构造函数
	public LinkedList() {
		this.head = null;
		this.size = 0;
	}
	
	//插入
	public void add(T data, int index) {
		if(index < 0 || index > this.size) {
			System.out.println("Index is error");
		}
		Node node = new Node(data);
		if(index == 0) {
			node.next = this.head;
			this.head = node;
			this.size ++;
			return; 
		}
		Node pre = this.head;
		for(int i = 0; i < index - 1; i++) {
			pre = pre.next;
		}
		node.next = pre.next;
		pre.next = node;
		this.size ++;
	}
	
	//删除
	public void remove(T data) {
		if(head == null) {
			System.out.println("No element to remove");
			return;
		}
		if(head != null && head.data.equals(data)) {
			head.next = head.next.next;
			this.size--;
		}
		Node cur = this.head;
		while(cur != null && cur.next != null) {
			if(cur.next.data.equals(data)) {
				cur.next = cur.next.next;
				this.size--;
			}
			else
				cur = cur.next;
		}
	}
	
	//遍历
	public void print() {
		Node node = head;
		System.out.print(node.getData());
		while(node.next != null) {
			node = node.next;
			System.out.print(" " + node.getData());
		}
		System.out.print("\n");
	}
	
	//主函数
	public static void main(String[] args) {
		LinkedList<Integer> linked = new LinkedList();
		for(int i = 0; i < 10; i++) {
			linked.add(10 - i, i);
			linked.print();
		}
		linked.add(33, linked.size);
		linked.print();
		linked.add(33, 0);
		linked.print();
		linked.add(33, 6);
		linked.print();
		linked.remove(33);
		linked.print();
	

注:头结点下标为0