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

Linked List - Insert, Remove

程序员文章站 2022-04-18 20:09:22
...

Main.java


public class Main {

	public static void main(String[] args) {
		LinkedList206<String> lnl = new LinkedList206<>();
		lnl.add("Kaipo");
		lnl.add("Han");
		lnl.add("Rex");
		lnl.add("Lana");
		lnl.add("Tiana");
		lnl.printAll();
		lnl.insertAt(0, "Mike");
		//String deleted = lnl.removeAt(0);
		System.out.println("Just added Mike to the list");
		lnl.printAll();
		//System.out.println(lnl.get(2));
		
		LinkedList206<Double> nums = new LinkedList206<>();
		nums.add(Math.PI);
		nums.add(Math.E);
		nums.add(4.0);
		nums.printAll();

	}

}

LinkedList206.java


public class LinkedList206<E> {

	Node206<E> head;
	
	public LinkedList206() {
		head = null;
	}
	
	public void add(E k) {
		Node206<E> n = new Node206<E>(k);
		if (head == null) {
			head = n;
		} else {
			//add the new node to the
			//end of the list.
			Node206<E> tmp = head;
			while (tmp.next != null) {
				tmp = tmp.next;
			}
			tmp.next = n;
		}
	}
	
	public void printAll() {
		Node206<E> tmp = head;
		while (tmp != null) {
			System.out.println(tmp.data);
			tmp = tmp.next;
		}
	}
	
	public E get(int index) {
		Node206<E> tmp = head;
		for (int i=0; i<index; i++) {
			tmp = tmp.next;
		}
		return tmp.data;		
	}
	
	public E removeAt(int index) {
		E result;
		Node206<E> tmp = head;
		if (index == 0) {
			result = head.data;
			head = head.next;
		} else {
			for (int i=0; i<index-1; i++) {
				tmp = tmp.next;
			}
			result = tmp.next.data;
			tmp.next = tmp.next.next;
		}
		return result;
	}
	
	public void insertAt(int index, E newData) {
		Node206<E> n = new Node206<E>(newData);
		Node206<E> tmp = head;
		if (index == 0) {
			n.next = head;
			head = n;
		} else {
			for (int i=0; i<index-1; i++) {
				tmp = tmp.next;
			}
			//make the new node point to the rest of the list
			n.next = tmp.next;
			
			//make the node before it, point to the new node
			tmp.next = n;
		}
	}
}

Node206.java


public class Node206<E> {
	E data;
	Node206<E> next;
	
	public Node206(E k) {
		data = k;
		next = null;
	}
}