원하는 형태의 이중 연결리스트 만들기. 일단 틀부터 짜자.
class DoubleNode{
DoubleNode llink;
DoubleNode rlink;
private String data;
public DoubleNode() {
this.data = null;
this.llink = null;
this.rlink = null;
}
public DoubleNode(String data) {
this.data = data;
this.llink = null;
this.rlink = null;
}
public String getData() {
return this.data;
}
public void setData(String data) {
this.data = data;
}
public DoubleNode getRlink(){
return this.rlink;
}
public void setRink(DoubleNode link) {
this.rlink = link;
}
}
**중간에 노드를 삽입하는 것과 끝에 계속 삽입해나가는 것은 엄밀히 다르다. newNode의 rlink값을 null로 변경 해주면 끝남.
class DoublyList{
private DoubleNode head;
public DoublyList() {
this.head = null;
}
public DoubleNode getHead() {
return this.head;
}
public void insertNode(DoublyList L, DoubleNode pre, String data) {
DoubleNode newNode = new DoubleNode(data);
if(L.head == null) {
L.head = newNode;
newNode.llink = null;
newNode.rlink = null;
}
else {
newNode.rlink = pre.llink;
pre.rlink = newNode;
newNode.llink = pre;
if(newNode.rlink != null) {
DoubleNode post = newNode.rlink;
post.rlink = newNode;
}
}
}
public void insertLastNode(DoublyList L, DoubleNode pre, String data) {
DoubleNode newNode2 = new DoubleNode(data);
if(L.head == null) {
L.head = newNode2;
newNode2.llink = null;
newNode2.rlink = null;
}
else {
newNode2.llink = pre.llink;
pre.rlink = newNode2;
newNode2.rlink = null;
}
}
public void print() {
DoubleNode tmp = this.head;
System.out.printf("result : ");
while(tmp != null) {
System.out.printf(tmp.getData());
tmp = tmp.rlink;
if(tmp != null) System.out.printf(", ");
}
System.out.println();
}
}
public class DoublyListEx01 {
public static void main(String[] args) {
DoublyList infos = new DoublyList();
DoubleNode pre = null;
infos.insertLastNode(infos, pre, "학번");
pre = infos.getHead();
infos.print(); //학번
infos.insertLastNode(infos, pre, "이름"); pre = pre.rlink;
infos.print(); //학번 이름
infos.insertLastNode(infos, pre, "학년"); pre = pre.rlink;
infos.print(); //학번 이름 학년
}
}
'Major > Data Structure & Algorithm' 카테고리의 다른 글
후위식 연산 (0) | 2022.04.22 |
---|---|
Stack , 괄호검사(Valid Braces), Infix to Postfix algorithm (0) | 2022.04.16 |
원형 연결 리스트 (0) | 2022.04.16 |
이중 연결 리스트의 삽입, 삭제 + (다항식 연산 ) (0) | 2022.04.13 |
연결리스트 노드 개수 카운팅,특정 노드 순서 바꾸기,첫번째 노드 삭제하기 ... (0) | 2022.04.03 |