package Datastructure;


public class Linkpractice {


Node head;

Node tail;

int size=0;

public class Node{

Node next;

Object data;

public Node(Object data){

this.next=null;

this.data=data;

}

}

public void addfirst(Object data){

if(head==null){

this.head= new Node(data);

size++;

}

else{

Node n = new Node(data);

n.next=this.head;

if(this.head.next==null){

this.tail=this.head;

}

this.head=n;

size++;

}

}

public void see(){

while(head.next !=null){

Object c =head.data;

System.out.println(c);

head=head.next;

}

System.out.println(tail.data);

}

public void addlast(Object data){

if(this.tail==null){

Node n=new Node(data);

this.head=n;

this.tail=n;

size++;

}

else{

Node n1=new Node(data);

this.tail.next=n1;

this.tail=n1;

size++;

}

}

public Node searchnode(int index){

Node s = this.head;

for(int i=0; i<index; i++){

s=s.next;

}

return s;

}

public void add(int index , Object data){

// 위치 0에 넣는다면 

if(index == 0){

addfirst(data);

}

else{// 위치 인덱스에 데이타를 넣겠다.

Node n= new Node(data);

Node pre=null;

pre=searchnode(index-1);

Node after=pre.next;

pre.next=n;

n.next=after;

size++;

//searchnode(index);

// n.next 뒤에 아무것도 안오는경우 

if(n.next==null){

this.tail=n;

}

}

}

// 처음 노드를 삭제 

public void removefirst(){

if(this.head==null){

return ;

}else{


Node tmp=null;

tmp=this.head;

this.head=null;

this.head=tmp.next;

size--;

}

}

// 중간 노드를 삭제 

public void remove (int index ){

if(index==0){

removefirst();

}

else{

Node tmp1=searchnode(index-1);

Node delnode=tmp1.next;

Node tmp2=searchnode(index+1); // 여기가 그냥 널로 들어가는군 delnode가 마지막이어도 

tmp1.next=tmp2;

if(delnode==this.tail){

//들어오고 

this.tail=tmp1;

}

delnode=null;

size--;

}

}

// 링크드리스트 사이즈 구하기 

public int linksize(){

return this.size ;

}

// 인덱스의 데이터 가져오기 

public Object getelement(int index){

Node tmp=searchnode(index);

return tmp.data;

}

public static void main(String[] args) {

Linkpractice p= new Linkpractice();

p.addfirst(1);

p.addfirst(2);

p.addfirst(3);

p.addlast(4);

p.add(4, 7);

p.remove(4); //짜놓은게 넣 포인트 날거 같았는데 실제로 나는줄 알았는데 

p.see();

}

}



'자료구조' 카테고리의 다른 글

배열 기반의 힙 , 우선순위 큐 구현 하기  (0) 2015.05.31
우선순위 큐 정리  (0) 2015.05.31
힙 정리  (0) 2015.05.30
큐 정리 소스 포함  (0) 2015.05.30
스택 정리 소스  (0) 2015.05.29
Posted by 이상욱1
,