Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) {
- LinkedList<String> list = new LinkedList<>();
- list.add("First");
- list.add("Second");
- list.add("Third");
- list.add("Fourth");
- list.add("Fifth");
- list.add("Sixth");
- list.printAll();
- list.delete(3);
- list.printAll();
- }
- }
- class LinkedList<T>{
- private Node head;
- private Node tail;
- private int size;
- private class Node{
- public T data;
- public Node next;
- public Node(T data){
- this.data = data;
- }
- }
- public LinkedList(){
- size = 0;
- }
- public void add(T data){
- if(null == head){
- head = new Node(data);
- tail = head;
- } else if(null == head.next) {
- head.next = new Node(data);
- tail = head.next;
- } else{
- tail.next = new Node(data);
- tail = tail.next;
- }
- size++;
- }
- // Semmilyen tail / size ellenorzes nincs megirva!
- public void delete(int position){
- if(position == 0){
- Node tmp = head;
- head = head.next;
- tmp.next = null;
- } else{
- Node n = head;
- // Eljut a megelozo nodeig
- for (int i = 0; i < position - 1; i++) {
- n = n.next;
- }
- Node tmp = n.next;
- n.next = tmp.next;
- tmp.next = null;
- }
- }
- public void printAll(){
- Node n = head;
- if(null != head){
- System.out.print("\n" + n.data + " --> ");
- while(null != n.next){
- n = n.next;
- System.out.print(n.data + " --> ");
- }
- System.out.print("null\n");
- } else {
- System.out.print("\nEmpty list!\n");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement