Java에서 처음부터 단독으로 링크 된 목록을 만들었습니다. 다음과 같이 코드는 다음과 같습니다Java에서 단일 링크 된 목록 반전
public class SingleLinkedList<Item>
{
private Node head;
private int size;
private class Node
{
Item data;
Node next;
public Node(Item data)
{
this.data = data;
this.next = null;
}
public Node(Item data, Node next)
{
this.data = data;
this.next = next;
}
//Getters and setters
public Item getData()
{
return data;
}
public void setData(Item data)
{
this.data = data;
}
public Node getNext()
{
return next;
}
public void setNext(Node next)
{
this.next = next;
}
}
public SingleLinkedList()
{
head = new Node(null);
size = 0;
}
public void add(Item data)
{
Node temp = new Node(data);
Node current = head;
while(current.getNext() != null)
{
current = current.getNext();
}
current.setNext(temp);
size++;
}
public void add(Item data, int index)
{
Node temp = new Node(data);
Node current = head;
for(int i=0; i<index && current.getNext() != null; i++)
{
current = current.getNext();
}
temp.setNext(current.getNext());
current.setNext(temp);
size++;
}
public Item get(int index)
{
if(index <= 0)
{
return null;
}
Node current = head;
for(int i=1; i<index; i++)
{
if(current.getNext() == null)
{
return null;
}
current = current.getNext();
}
return current.getData();
}
public boolean remove(int index)
{
if(index < 1 || index > size())
{
return false;
}
Node current = head;
for(int i=1; i<index; i++)
{
if(current.getNext() == null)
{
return false;
}
current = current.getNext();
}
current.setNext(current.getNext().getNext());
size--;
return true;
}
public String toString()
{
Node current = head.getNext();
String output = "";
while(current != null)
{
output+=current.getData().toString()+" ";
current = current.getNext();
}
return output;
}
public int size()
{
return size;
}
public void reverse()
{
Node current = head;
Node prevNode = null;
Node nextNode;
while(current!=null)
{
nextNode = current.getNext();
current.setNext(prevNode);
prevNode = current;
current = nextNode;
System.out.println(prevNode.getData());
}
head = prevNode;
}
}
당신이 볼 수 있듯이, 나는 단지 클래스의 역 기능을 추가했습니다.
그러나 실제로 클래스를 사용하여 시도했을 때 역순으로 시도한 후에 NullPointerException을 발생 시켰습니다.
기능을 확인하기 위해 TEST라는 다른 클래스를 사용했습니다.
1 2 3 4 5
null
1
2
3
4
5
Exception in thread "main" java.lang.NullPointerException
at SingleLinkedList.toString(SingleLinkedList.java:129)
at TEST.main(TEST.java:20)
내가 그 복용하지 값 여부를 확인하기 위해 prevNode의 값을 출력하려고 ...하지만은 다음과 같이
public class TEST
{
public static void main(String[] args)
{
SingleLinkedList<Integer> list = new SingleLinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
System.out.println(list.toString());
list.reverse();
System.out.println(list.toString());
}
}
출력은 다음과 같이 코드입니다. 무엇을할까요?
를 작동하고 당신의 SingleLinkedList.java toString() 메소드에 가장 좋은 방법은 종이와 연필을 사용하고 예제를 그리고 포인터가 프로그램의 작업에 따라 어떻게 바뀌는 지입니다. – Henry
나는 그 모든 것을 시도했다. 아무것도 찾을 수 없습니다. 내가 그 일을하고 있지만 아직도 나는 붙어있다. 나 좀 도와 줄 수있어? –