yeahzzz 2022. 4. 16. 16:25

원하는 형태의 이중 연결리스트 만들기. 일단 틀부터 짜자. 

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(); //학번 이름 학년 
	}
}