티스토리 뷰


public class Node {

int data;

Node next;

public Node(int data) {

this.data = data;

next = null;

}

public int getData() {

return data;

}

public void setData(int data) {

this.data = data;

}

public Node getNext() {

return next;

}

public void setNext(Node next) {

this.next = next;

}

}



import java.util.Scanner;


public class LinkedList {

Node head;

boolean find(int data)

{

Node current = head;

while(current != null)

{

if(current.data == data) {

return true;

}

current = current.next;

}

return false; 

}

void insert(int data)

{

Node newnode = new Node(data);

Node pre = head;

Node current = head;

if(head == null)

head = newnode;

else

{

while(current != null && current.data < data)

{

pre = current;

current = current.next;

}

if(pre == head && current == head) //연결리스트에 맨 앞에 새로운 노드를 삽입해야 하는 경우

{

newnode.next = head;

head = newnode;

}

else if(current==null) //맨 마지막에 삽입 해야 한다면

pre.next = newnode; //노드를 연결리스트의 맨 뒤에 삽입한다.

else

{

pre.next = newnode;

newnode.next = current;

}

}

}

void delete(int data)

{

if(!find(data))

{

System.out.println(data+"이 연결리스트 안에 없기 때문에 삭제 할 수 없습니다.");

return;

}

else

{

Node pre = null;

Node current = head;

while(current != null && current.data != data)

{

pre = current;

current= current.next;

}

if(pre == null) //삭제하려는게 연결리스트의 맨 앞인 경우

{

head = head.next;

}

else if(current == null) //삭제 하려는게 연결리스트의 맨 뒤인 경우 

{

pre = null;

}

else //중간에 있는 노드를 삭제하려고 하는 경우

{

pre.next = current.next;

current.next = null;

}

System.out.println(data + "를 성공적으로 삭제했습니다.");

}

}

void display()

{

Node current = head;

while(current != null)

{

System.out.print(current.data + " ");

current = current.next;

}

System.out.println();

}

public static void main(String args[]) {

LinkedList list = new LinkedList();

while(true)

{

System.out.println("1.탐색 2.삽입 3.삭제 4.출력 5.종료 중 숫자를 하나 입력해주세요");

Scanner sc = new Scanner(System.in);

int value = sc.nextInt();

if(value == 5) return;

switch(value)

{

case 1:

System.out.print("찾으려는 값을 입력해주세요 ");

Scanner b = new Scanner(System.in);

int findvalue = b.nextInt();

boolean bool = list.find(findvalue);

if(bool) System.out.println(findvalue+"이 연결리스트 안에 있습니다.");

else System.out.println(findvalue+"이 연결리스트 안에 없습니다.");

break;

case 2:

System.out.print("무엇을 삽입 하시겠습니까? ");

Scanner a = new Scanner(System.in);

list.insert(a.nextInt());

break;

case 3:

System.out.print("무엇을 삭제 하시겠습니까? ");

Scanner c = new Scanner(System.in);

int deletevalue = c.nextInt();

list.delete(deletevalue);

break;

case 4:

System.out.println("모든 데이터를 출력하겠습니다.");

list.display();

break;

default:

break;

}

}

}

}

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함