Skip to content

Instantly share code, notes, and snippets.

@ekal901
Last active June 13, 2020 11:22
Show Gist options
  • Save ekal901/9fa2ed8e8644a0c376cf9330fa5495b9 to your computer and use it in GitHub Desktop.
Save ekal901/9fa2ed8e8644a0c376cf9330fa5495b9 to your computer and use it in GitHub Desktop.
LinkedList 직접 구현
package com.test;
public class Contact {
String name;
String tel; // 010-1111-2222
String gender;
String birthDate; // 1991/09/01
public Contact() {
}
public Contact(String name, String tel, String gender, String birthDate) {
this.name = name;
this.tel = tel;
this.gender = gender;
this.birthDate = birthDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
@Override
public String toString() {
return "이름: " + this.name + " 전화번호: " + this.tel + " 성별 : " + this.gender + " 생년월일 : " + this.birthDate;
}
public String print() {
return this.name + " | " + this.tel + " | " + this.gender + " | " + this.birthDate;
}
}
package com.test.list;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<Data> implements Iterable<Data> {
private Node<Data> head;
private Node<Data> tail;
private int size;
@Override
public Iterator<Data> iterator() {
return new ListIterator(head);
}
public static class Node<Data> {
private Data data;
private Node<Data> next;
public Node(Data data) {
this.data = data;
this.next = null;
}
public Data getData() {
return data;
}
}
public void add(Data data) {
Node<Data> newNode = new Node<Data>(data);
if (size == 0) {
head = newNode;
size++;
tail = head;
} else {
tail.next = newNode;
tail = newNode; // 마지막 노드를 갱신
size++;
}
}
// index에 해당하는 Node 리턴
public Node<Data> getNode(int index) {
Node<Data> node = head;
for (int i = 0; i < index; i++) {
node = node.next;
}
return node;
}
public int size() {
return size;
}
public String toString() {
if(head == null) {
return "[]";
}
Node<Data> temp = head;
String str = "";
while(temp.next != null) {
str += temp.getData().toString();
// str += temp.data.getName() + " | " + temp.data.getTel() + " | " + temp.data.getGender() + " | " + temp.data.getBirthDate()+ "\n";
temp = temp.next;
}
str += temp.getData().toString();
// str += temp.data.getName() + " | " + temp.data.getTel() + " | " + temp.data.getGender() + " | " + temp.data.getBirthDate();
return str;
}
public void Remove(Node<Data> node) {
// if first node,
if (head == node) {
head = node.next;
} else {
// find the prev node
Node<Data> prev = this.head;
while (prev.next != node && prev != tail) {
prev = prev.next;
}
// found successfully, remove the node
if (prev != tail) {
prev.next = node.next;
}
}
size--;
}
class ListIterator implements Iterator<Data> {
Node<Data> cursor;
ListIterator(Node<Data> startingPoint) {
this.cursor = startingPoint;
}
@Override
public boolean hasNext() {
return cursor != null;
}
public Data next() {
if (cursor == null)
throw new NoSuchElementException();
Data data = cursor.getData(); // 현재 데이터 가져옴
cursor = cursor.next;
return data;
}
}
}
package com.test.list;
import com.test.Contact;
import org.junit.jupiter.api.Assertions;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static org.junit.jupiter.api.Assertions.*;
class LinkedListTest {
LinkedList<Contact> makeDummyList() {
LinkedList<Contact> list = new LinkedList<>();
list.add(new Contact("담히", "010-1111-2222", "여", "1991/09/01"));
list.add(new Contact("라이언", "010-1234-5678", "남", "1995/07/22"));
list.add(new Contact("짠우", "010-8888-4444", "남", "1994/01/05"));
return list;
}
@org.junit.jupiter.api.Test
// 리스트에 0개 있을때 hasNext (false), next (no such element exception) 동작이 예상한대로 동작하는지
void iteratorEmptyTest() {
LinkedList<Contact> list = new LinkedList<>();
Iterator<Contact> iter = list.iterator();
assertFalse(iter.hasNext());
assertThrows(NoSuchElementException.class, iter::next);
}
@org.junit.jupiter.api.Test
// 리스트에 엘레먼트가 1개 있을때, has next가 한번 true가 되는지 확인, next가 한번 동작하고 exception을 내는지 확인
void iteratorOneItemTest() {
LinkedList<Contact> list = new LinkedList<>();
list.add(new Contact("담히", "010-1111-2222", "여", "1991/09/01"));
int hasNextCnt = 0;
Iterator<Contact> iter = list.iterator();
while (iter.hasNext()) {
hasNextCnt++;
iter.next();
}
assertEquals(1, hasNextCnt);
// when everything is over
assertFalse(iter.hasNext());
assertThrows(NoSuchElementException.class, iter::next);
}
/**
* 리스트에 엘레먼트가 n개 있을때 has next가 n번 되는지 확인, next가 n번 '순서대로' 잘 반환하고 exception을 반환하는지 확인
*/
@org.junit.jupiter.api.Test
void iteratorMultipleItemsTest() {
LinkedList<Contact> list = makeDummyList();
int hasNextCnt = 0;
Iterator<Contact> iter = list.iterator();
while (iter.hasNext()) {
Contact data = list.getNode(hasNextCnt).getData();
Assertions.assertSame(data, iter.next());
hasNextCnt++;
}
assertEquals(list.size(), hasNextCnt);
// when the iteration is over
assertFalse(iter.hasNext());
assertThrows(NoSuchElementException.class, iter::next);
}
@org.junit.jupiter.api.Test
void addTest() {
LinkedList<Contact> list = makeDummyList();
LinkedList.Node<Contact> node = list.getNode(0);
assertEquals("010-1111-2222", node.getData().getTel());
node = list.getNode(1);
assertEquals("010-1234-5678", node.getData().getTel());
node = list.getNode(2);
assertEquals("010-8888-4444", node.getData().getTel());
}
@org.junit.jupiter.api.Test
void removeTest() {
// #1
LinkedList<Contact> list = makeDummyList();
list.Remove(list.getNode(0));
assertEquals("010-1234-5678", list.getNode(0).getData().getTel());
// else
list = makeDummyList();
list.Remove(list.getNode(1));
assertEquals("010-1111-2222", list.getNode(0).getData().getTel());
assertEquals("010-8888-4444", list.getNode(1).getData().getTel());
}
}
package com.test;
import com.test.list.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LinkedList<Contact> contactList = new LinkedList<>();
boolean isRun = true;
while (isRun) {
System.out.println("주소 관리 검색 프로그램");
System.out.println("1. 등 록");
System.out.println("2. 출 력");
System.out.println("3. 삭 제");
System.out.println("4. 종 료");
System.out.println("명령어를 선택하세요.");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
switch(num) {
case 1 :
Contact contact = addContact(sc);
contactList.add(contact);
break;
case 2 :
System.out.println("이름 | 전화번호 | 성별 | 생년월일");
/* Iterator<Contact> iter = contactList.iterator();
while (iter.hasNext()) {
Contact item = iter.next();
System.out.println(item.toString());
}*/
/*for (Contact cont : contactList) {
System.out.println(cont.toString());
}*/
contactList.forEach(e -> System.out.println(e.toString()));
break;
case 3 :
System.out.println("삭제할 전화번호를 입력하세요.");
String tel = sc.next();
LinkedList.Node<Contact> node = null;
for(int i = 0; i < contactList.size(); i++) {
node = contactList.getNode(i);
if(node.getData().getTel().equals(tel)) {
break;
}
}
contactList.Remove(node);
// contactList.Remove(tel);
// 1. find a node that has specified telephone number.
// 2. delete that node
break;
case 4 :
System.out.println("종료합니다.");
sc.close();
isRun = false;
break;
default :
System.out.println("잘못된 입력입니다.");
break;
}
}
}
public static Contact addContact(Scanner sc) {
Contact contact = new Contact();
System.out.println("이름을 입력하세요.");
String name = sc.next();
System.out.println("전화번호를 입력하세요.");
String tel = sc.next();
System.out.println("성별을 입력하세요.");
String gender = sc.next();
System.out.println("생년월일을 입력하세요.");
String birthDate = sc.next();
contact.setName(name);
contact.setTel(tel);
contact.setGender(gender);
contact.setBirthDate(birthDate);
return contact;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment