개발/Java

[Java] Java LinkedList 구현

hojak99 2015. 11. 10. 11:00
public class LinkedList {
	private Node head;
	private Node tail;
	public String a;

	private class Node {
		private String data;		
		private Node next;

		public Node(String a) {
			this.data = a;
			this.next = null;
		}
	}

	public void addstart(String a) {
		Node newnode = new Node(a);
		newnode.next = head;
		head = newnode;
		tail = head;

	}

	public void add(String a) {
		Node newnode = new Node(a);
		tail.next = newnode;
		tail = newnode;
	}

	public void insert(String a, int b) {
		Node i = head;

		for (int k = 0; k < b - 1; k++) {
			i = i.next;
		}
		Node tmp = i;

		Node tmp_1 = i.next;

		Node newnode = new Node(a);
		tmp.next = newnode;
		newnode.next = tmp_1;
	}

	public void reverse() {
		Node tmp = tail;
		tail = head;
		head = tmp;
		///
		head.next = tail.next.next;
		head.next.next=null;
		head.next.next =tail.next;
		head.next.next.next=null;
		head.next.next.next=tail;
		head.next.next.next.next = null;
		tail=head.next.next; 
	}
	public void print() {
		Node ptr = head;
		while (ptr != null) {
			System.out.println(ptr.data);
			ptr = ptr.next;
		}
	}
	public void delete(){
		tail.next = null; 
	}
}


public class main {
	public static void main(String args[]){
		LinkedList list = new LinkedList();
		list.addstart("monday");
		list.add("wednesday");
		list.add("sunday");
		list.insert("friday", 2);
		list.print();
		System.out.println("");
		System.out.println("");
		list.reverse();
		list.print();
		System.out.println("");
		System.out.println("");
		list.delete();
		list.print();
	}
}

/*
    monday
    wednesday
    friday
    sunday


    sunday
    friday
    wednesday
    monday


    sunday
    friday
    wednesday
*/


반응형