2011-11-07 4 views
1

나는 프로그램을 끝내려고 노력하고 있는데, 나는 현장에서 붙 잡혔다. 내 deleteCurrentNode 메서드는 부분적으로 만 작동합니다. 어떤 이유로 링크 된 목록을 탐색하여 currentNode를 찾지 못하면 찾지 않습니다. 누군가 그것을 작동시키는 방법에 대한 조언을 제게 제공 할 수 있습니까? 목록이 비어있는 경우단일 링크 된 목록에서 현재 노드를 삭제하는 방법은 무엇입니까?

  1. :

    이 방법 자체는도 4 개의 조건을 검사한다.

  2. currentNode가 null 인 경우.
  3. currentNode가 목록의 첫 번째 노드 인 경우.
  4. currentNode가 목록의 어딘가에있는 경우.

기타 조건은 (내 지식으로) 작동합니다. 4는 문제가있는 곳입니다.

public class LinkedList 
{ 
private Node currentNode; 
private Node firstNode; 
private int nodeCount; 

public static void main(String[] args) 
{ 
LinkedList test; 
String dataTest; 
test = new LinkedList(); 
dataTest = "abcdefghijklmnopqrstuvwxyz"; 
for(int i=0; i< dataTest.length(); i++) { test.insert(new String(new char[] { dataTest.charAt(i) })); } 
System.out.println("[1] "+ test); 

    for(int i=0; i< dataTest.length(); i++) { test.deleteCurrentNode(); } 
    System.out.println("[2] "+test); 

    for(int i=0; i< dataTest.length(); i++) 
    { 
    test.insertBeforeCurrentNode(new String(new char[] { dataTest.charAt(i) })); 
    if(i%2 == 0) { test.first(); } else { test.last(); } 
    } 

    System.out.println("[3] "+test); 

    for(int i=0; i< dataTest.length(); i++) { test.last(); test.deleteCurrentNode(); } 
     System.out.println("[4] "+test); 


     for(int i=0; i< dataTest.length(); i++) { test.insert(new String(new char[] { dataTest.charAt(i) })); test.last(); } 
     System.out.println("[5] "+test); 

    while(!test.isEmpty()) { test.deleteFirstNode(); } 
    System.out.println("[6] "+test); 

    for(int i=0; i< dataTest.length(); i++) { test.insert(new String(new char[] { dataTest.charAt(i) })); test.last(); } 
    System.out.println("[7] "+test); 

    while(!test.isEmpty()) { test.deleteFirstNode(false); } 
    System.out.println("[8] "+test); 

    for(int i=0; i< dataTest.length(); i++) { test.insertBeforeCurrentNode(new String(new char[] { dataTest.charAt(i) })); test.first(); } 
    System.out.println("[9] "+test); 
} 

public LinkedList() 
{ 
    setListPtr(null); 
    setCurrent(null); 
    nodeCount = 0; 
} 

public boolean atEnd() 
{ 
    //checkCurrent(); 
    return getCurrent().getNext() == null;  
} 

public boolean isEmpty() 
{ 
    return getListPtr() == null; 
} 

public void first() 
{ 
    setCurrent(getListPtr()); 
} 

public void next() 
{ 
    checkCurrent(); 
    if (atEnd()) {throw new InvalidPositionInListException("You are at the end of the list. There is no next node. next().");} 
    setCurrent(this.currentNode.getNext()); 
} 

public void last() 
{ 
    if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");} 

    while (!atEnd()) 
    { 
     setCurrent(getCurrent().getNext()); 
    } 

} 

public Object getData() 
{ 
    return getCurrent().getData(); 
} 

public void insertBeforeCurrentNode(Object bcNode) //beforeCurrentNode 
{ 
    Node current; 
    Node hold; 
    boolean done; 
    hold = allocateNode(); 
    hold.setData(bcNode); 
    current = getListPtr(); 
    done = false; 
    if (isEmpty()) 
    { 
     setListPtr(hold); 
     setCurrent(hold);  
    } 

    else if (getCurrent() == getListPtr()) 
    { 
    // System.out.println("hi" + hold); 
     hold.setNext(getCurrent()); 
     setListPtr(hold); 
    } 

    else if (!isEmpty() && getCurrent() != getListPtr()) 
    { 
     while (!done && current.getNext() != null) 
     { 
      //System.out.println("in else if " + hold); 
      if (current.getNext() == getCurrent()) 
      { 
       //previous.setNext(hold); 
       //System.out.println("hi"+ "yo" + " " + getListPtr()); 
       hold.setNext(current.getNext()); 
       current.setNext(hold); 
       done = true; 
      } 

      //previous = current; 
      current = current.getNext(); 
     } 

    } 
    //System.out.println("current " + getCurrent()); 
    //System.out.println("pointer " + getListPtr()); 

} 

public void insertAfterCurrentNode(Object acNode) //afterCurrentNode 
{ 
    Node hold; 
    hold = allocateNode(); 
    hold.setData(acNode); 
    if (isEmpty()) 
    { 
     setListPtr(hold); 
     setCurrent(hold); 
     //System.out.println(hold + " hi"); 
    } 

    else 
    { 
     //System.out.println(hold + " hia"); 
     hold.setNext(getCurrent().getNext()); 
     getCurrent().setNext(hold); 
    } 
} 

public void insert(Object iNode) 
{ 
    insertAfterCurrentNode(iNode); 
} 

public Object deleteCurrentNode() 
{ 
    //System.out.println("in delete current"); 
    Object nData; 
    Node previous; 

    if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");} //if list is empty throw exception 

    checkCurrent(); //check if currentNode is null, method throws exception if it is. 

    nData = getCurrent().getData(); 

    if (getCurrent() == getListPtr()) 
    { 
     setListPtr(getCurrent().getNext()); 
     setCurrent(getCurrent().getNext()); 
     nodeCount = nodeCount -1; 
    } 

    else 
    { 
     previous = getListPtr(); 
     while (previous.getNext() != getCurrent()) 
     { 
      previous = previous.getNext(); 
      //System.out.println("test"+ previous); 
     } 


     if (getCurrent().getNext() != null) 
     { 
      previous.setNext(null); 
     } 

     previous.setNext(getCurrent().getNext());  } 

    return nData; 
} 

public Object deleteFirstNode(boolean toDelete) 
{ 
    if (toDelete) 
    { 
     setListPtr(null); 
    } 
    return getListPtr(); 
} 

public Object deleteFirstNode() 
{ 
    Object deleteFirst; 
    deleteFirst = deleteFirstNode(true); 
    return deleteFirst; 
} 

public int size() 
{ 
    return this.nodeCount; 
} 

public String toString() 
{ 
    String nodeString; 
    Node sNode; 
    sNode = getListPtr(); 
    //System.out.println(nodeCount); 
    nodeString = ("List contains " + nodeCount + " nodes"); 
    while (sNode != null) 
    { 
     nodeString = nodeString + " " +sNode.getData(); 
     sNode = sNode.getNext(); 
    } 
    return nodeString; 
} 

private Node allocateNode() 
{ 
    Node newNode; 
    newNode = new Node(); 
    nodeCount = nodeCount + 1; 
    return newNode; 
} 

private void deAllocateNode(Node dNode) 
{ 
    dNode.setData(null); 
} 

private Node getListPtr() 
{ 
    return this.firstNode; 
} 

private void setListPtr(Node pNode) 
{ 
    this.firstNode = pNode; 
} 

private Node getCurrent() 
{ 
    return this.currentNode; 
} 

private void setCurrent(Node cNode) 
{ 
    this.currentNode = cNode; 
} 

private void checkCurrent() 
{ 
    if (getCurrent() == null) {throw new InvalidPositionInListException("Current node is null and is set to an invalid position within the list! checkCurrent()");} 
} 

/**NODE CLASS ----------------------------------------------*/ 

    private class Node 
    { 
     private Node next; //serves as a reference to the next node 
     private Object data; 

     public Node() 
     { 
      this.next = null; 
      this.data = null; 
     } 


     public Object getData() 
     { 
      return this.data; 
     } 

     public void setData(Object obj) 
     { 
      this.data = obj; 
     } 

     public Node getNext() 
     { 
      return this.next; 
     } 

     public void setNext(Node nextNode) 
     { 
      this.next = nextNode; 
     } 

     public String toString() 
     { 
      String nodeString; 
      Node sNode; 
      sNode = getListPtr(); 
      //System.out.println(nodeCount); 
      nodeString = ("List contains " + nodeCount + " nodes"); 
      while (sNode != null) 
      { 
       nodeString = nodeString + " " +sNode.getData(); 
       sNode = sNode.getNext(); 
      } 
      return nodeString; 
     } 
    } 


} 

[4] [2]

주와 같은 읽어야은 (목록 0 노드가 포함되어 있습니다.) : 이미있는 등 더 이상 변수/방법/사용 할 수 없습니다. 그리고 헤드 노드를 사용할 수 없습니다. 같은 목록의 한 노드 대표는 노드 클래스가있는 경우

+0

실제로 여기서는 아무 것도하지 않으므로 문제가 무엇인지 이해하지 못합니다. – leo

+0

"이전"에있는 노드를 삭제하지 않습니다 – leo

+0

내 프로그램의 잘못된 버전을 복사했습니다. 미안합니다. 업데이트되었습니다. 메서드 자체는 삭제되는 현재 노드의 데이터 부분을 반환해야하지만, 지금은 이전 변수가 currentNode에 있도록 목록을 탐색하려고합니다. – solllodolllo

답변

1
public class LinkedList 
{ 
private Node currentNode; 
private Node firstNode; 
private int nodeCount; 


public static void main(String[] args) 
{ 
    String  data; 
    Object  hold; 
    LinkedList list; 

    data = "abcdefghijklmnopqrstuvwxyz"; 
    hold = null; 
    list = new LinkedList(); 

    for(int i=0; i< data.length(); i++) { list.insert(new String(new char[] { data.charAt(i) })); } 
    System.out.println("[1] "+list); 

    for(int i=0; i< data.length(); i++) { list.deleteCurrentNode(); } 
    System.out.println("[2] "+list); 

    for(int i=0; i< data.length(); i++) 
    { 
    list.insertBeforeCurrentNode(new String(new char[] { data.charAt(i) })); 
    if(i%2 == 0) { list.first(); } else { list.last(); } 
    } 

    System.out.println("[3] "+list); 

    for(int i=0; i< data.length(); i++) { list.last(); list.deleteCurrentNode(); } 
    System.out.println("[4] "+list); 


    for(int i=0; i< data.length(); i++) { list.insert(new String(new char[] { data.charAt(i) })); list.last(); } 
    System.out.println("[5] "+list); 

    while(!list.isEmpty()) { list.deleteFirstNode(); } 
    System.out.println("[6] "+list); 

    for(int i=0; i< data.length(); i++) { list.insert(new String(new char[] { data.charAt(i) })); list.last(); } 
    System.out.println("[7] "+list); 

    while(!list.isEmpty()) { list.deleteFirstNode(false); } 
    System.out.println("[8] "+list); 

    for(int i=0; i< data.length(); i++) { list.insertBeforeCurrentNode(new String(new char[] { data.charAt(i) })); list.first(); } 
    System.out.println("[9] "+list); 

    list.first(); 
    list.next(); 
    list.deleteFirstNode(true); 
    list.deleteCurrentNode(); 
    for(int i=0; i< 5; i++) { hold = list.getData(); list.next(); } 
    for(int i=0; i< 10; i++) { list.next(); } 
    list.insertAfterCurrentNode(hold); 
    list.first(); 
    list.next(); 
    hold = list.getData(); 
    list.deleteCurrentNode(); 
    for(int i=0; i<9; i++) {list.deleteCurrentNode(); list.last(); } 
    list.insert(hold); 
    list.first(); 
    list.next(); 
    list.next(); 
    list.next(); 
    list.deleteFirstNode(false); 
    hold = list.getData(); 
    list.deleteCurrentNode(); 
    list.last(); 
    list.insertAfterCurrentNode(hold); 
    list.deleteFirstNode(); 
    list.deleteFirstNode(); 
    hold = list.getData(); 
    list.deleteFirstNode(); 
    list.last(); 
    list.insertBeforeCurrentNode(hold); 
    list.first(); 
    for(int i=0; i<6; i++) { list.next(); } 
    hold = list.getData(); 
    list.deleteCurrentNode(); 
    list.last(); 
    list.insertBeforeCurrentNode(hold); 
    list.first(); 
    list.deleteCurrentNode(); 
    list.deleteCurrentNode(); 
    hold = list.getData(); 
    list.deleteCurrentNode(); 
    for (int i=0; i< 7; i++) { list.next(); } 
    list.insertBeforeCurrentNode(hold); 
    for (int i=0; i< 4; i++) { list.first(); list.deleteCurrentNode(); } 
    System.out.println("\n\n"+list); 


} 

public LinkedList() 
{ 
    setListPtr(null); 
    setCurrent(null); 
    nodeCount = 0; 
} 

public boolean atEnd() 
{ 
    if (getCurrent() != null) 
     { 
     return getCurrent().getNext() == null; 
     } 
     return true; 

} 

public boolean isEmpty() 
{ 
    return getListPtr() == null; 
} 

public void first() 
{ 
    setCurrent(getListPtr()); 
} 

public void next() 
{ 
    checkCurrent(); 
    if (atEnd()) {throw new InvalidPositionInListException("You are at the end of the list. There is no next node. next().");} 
    setCurrent(this.currentNode.getNext()); 
} 

public void last() 
{ 
    if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");} 

    while (!atEnd()) 
    { 
     setCurrent(getCurrent().getNext()); 
    } 

} 

public Object getData() 
{ 
    return getCurrent().getData(); 
} 

public void insertBeforeCurrentNode(Object bcNode) //beforeCurrentNode 
{ 
    Node current; 
    Node hold; 
    boolean done; 
    hold = allocateNode(); 
    hold.setData(bcNode); 
    current = getListPtr(); 
    done = false; 
    if (isEmpty()) 
    { 
     setListPtr(hold); 
     setCurrent(hold);  
    } 

    else if (getCurrent() == getListPtr()) 
    { 
    // System.out.println("hi" + hold); 
     hold.setNext(getCurrent()); 
     setListPtr(hold); 
    } 

    else if (!isEmpty() && getCurrent() != getListPtr()) 
    { 
     while (!done && current.getNext() != null) 
     { 
      //System.out.println("in else if " + hold); 
      if (current.getNext() == getCurrent()) 
      { 
       //previous.setNext(hold); 
       //System.out.println("hi"+ "yo" + " " + getListPtr()); 
       hold.setNext(current.getNext()); 
       current.setNext(hold); 
       done = true; 
      } 

      //previous = current; 
      current = current.getNext(); 
     } 

    } 
    //System.out.println("current " + getCurrent()); 
    //System.out.println("pointer " + getListPtr()); 

} 

public void insertAfterCurrentNode(Object acNode) //afterCurrentNode 
{ 
    Node hold; 
    hold = allocateNode(); 
    hold.setData(acNode); 
    if (isEmpty()) 
    { 
     setListPtr(hold); 
     setCurrent(hold); 
     //System.out.println(hold + " hi"); 
    } 

    else 
    { 
     //System.out.println(hold + " hia"); 
     hold.setNext(getCurrent().getNext()); 
     getCurrent().setNext(hold); 
    } 
} 

public void insert(Object iNode) 
{ 
    insertAfterCurrentNode(iNode); 
} 

public Object deleteCurrentNode() 
{ 
    //System.out.println("in delete current"); 
    Object nData; 
    Node previous; 

    if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");} //if list is empty throw exception 

    checkCurrent(); //check if currentNode is null, method throws exception if it is. 

    nData = getCurrent().getData(); 

    if (getCurrent() == getListPtr()) 
    { 
     setListPtr(getCurrent().getNext()); 
     setCurrent(getCurrent().getNext()); 
     nodeCount = nodeCount -1; 
    } 

    else 
    { 
     previous = getListPtr(); 
     //System.out.println(getCurrent()); 
     //System.out.println(previous + "ptrb "); 
     while (previous.getNext() != getCurrent()) 
     { 
      previous = previous.getNext(); 
      //System.out.println("test"+ previous); 
     } 

     //System.out.println(previous.getNext() == getCurrent()); 

     if (previous.getNext() == getCurrent()) 
     { 
      //System.out.println("say hi"); 
      previous.setNext(getCurrent().getNext()); 
      deAllocateNode(getCurrent()); 
      setCurrent(previous); 
      nodeCount = nodeCount - 1; 
     } 

     previous.setNext(getCurrent().getNext()); 

    } 

    return nData; 
} 

public Object deleteFirstNode(boolean toDelete) 
{ 
    if (toDelete) 
    { 
     setCurrent(getListPtr().getNext()); 
    } 
    deAllocateNode(getListPtr()); 
    setListPtr(getListPtr().getNext()); 

    nodeCount = nodeCount - 1; 
    return getListPtr(); 
} 

public Object deleteFirstNode() 
{ 
    Object deleteFirst; 
    deleteFirst = deleteFirstNode(true); 
    //System.out.println("called"); 
    return deleteFirst; 
} 

public int size() 
{ 
    return this.nodeCount; 
} 

public String toString() 
{ 
    String nodeString; 
    Node sNode; 
    sNode = getListPtr(); 
    //System.out.println(nodeCount); 
    nodeString = ("List contains " + nodeCount + " nodes"); 
    while (sNode != null) 
    { 
     nodeString = nodeString + " " +sNode.getData(); 
     sNode = sNode.getNext(); 
    } 
    return nodeString; 
} 

private Node allocateNode() 
{ 
    Node newNode; 
    newNode = new Node(); 
    nodeCount = nodeCount + 1; 
    return newNode; 
} 

private void deAllocateNode(Node dNode) 
{ 
    dNode.setData(null); 
} 

private Node getListPtr() 
{ 
    return this.firstNode; 
} 

private void setListPtr(Node pNode) 
{ 
    this.firstNode = pNode; 
} 

private Node getCurrent() 
{ 
    return this.currentNode; 
} 

private void setCurrent(Node cNode) 
{ 
    this.currentNode = cNode; 
} 

private void checkCurrent() 
{ 
    if (getCurrent() == null) {throw new InvalidPositionInListException("Current node is null and is set to an invalid position within the list! checkCurrent()");} 
} 

/**NODE CLASS ----------------------------------------------*/ 

    private class Node 
    { 
     private Node next; //serves as a reference to the next node 
     private Object data; 

     public Node() 
     { 
      this.next = null; 
      this.data = null; 
     } 


     public Object getData() 
     { 
      return this.data; 
     } 

     public void setData(Object obj) 
     { 
      this.data = obj; 
     } 

     public Node getNext() 
     { 
      return this.next; 
     } 

     public void setNext(Node nextNode) 
     { 
      this.next = nextNode; 
     } 

     public String toString() 
     { 
      String nodeString; 
      Node sNode; 
      sNode = getListPtr(); 
      //System.out.println(nodeCount); 
      nodeString = ("List contains " + nodeCount + " nodes"); 
      while (sNode != null) 
      { 
       nodeString = nodeString + " " +sNode.getData(); 
       sNode = sNode.getNext(); 
      } 
      return nodeString; 
     } 
    } 


    } 

귀하의 기고에 감사드립니다. 그들은 내 문제를 해결하는 데 도움이되었습니다. (다소 모호하지만)

다른 사람이 비슷한 문제를 겪은 경우 참조 도구로 사용할 수 있도록 내 자신의 질문에 대답하고 있습니다.

다시 한 번 감사드립니다.

1

: 귀하의 목록에 구현하면보다

public class Node{ 
public Object value; 
public Node next; 

public Node(){ 

} 

public Node(Object p){ 
    value= p; 
} 

public String toString(){ 
    return "" + this.value.toString(); 
} 
} 

을 (만 제거하는 방법) 당신이 가진 것 (의은으로 myList를 가정 해 봅시다) :

public class MyList{ 
    private Node head; 

public Object removeFirst(){ 
    if(head == null){ 
     return null; 
    } 

    Object o= head.value; 
    head= head.next; 
    return o; 
} 

    // remove by index 
public Object remove(int i){ 
    int n= this.size(); 
    if(i<0 || i>=n){ 
     return null; 
    } 

    if(i==0){ 
     return this.removeFirst(); 
    } 

    int k=0; 
    Node t= head; 

    while(k < i-1){ 
     t= t.next; 
     k= k+1; 
    } 

    Object o= t.next.value; 
    t.next= t.next.next; 

    return o; 
} 

    //remove by object 
    public boolean remove(Object o){ 
    int k= this.indexOf(o); 
    if(k<0){ 
     return false; 
    } 
    this.remove(k); 

    return true; 
} 

    //not necessary, but you may study the logic 
    public Object removeLast(){ 
    Object o= null; 
    if(head!=null){ 
     if(head.next==null){ 
      o= head.value; 
      head= null; 
     }else{ 
      Node t= head.next; 
      while(t.next.next != null){ 
       t= t.next; 
      } 
      o= t.next.value; 
      t.next= null; 
     } 
    } 
    return o; 
} 
} 

편집 : 배열에 요소가 하나만 있으면 몇 가지 문제가 있습니다. 마지막() 메소드의 예를 들어

->

while (!atEnd()) { 
     setCurrent(getCurrent().getNext()); 
    } 
+0

제 구현을 위해서는 currentNode와 firstNode라는 두 개의 다른 노드가 있어야합니다. 나는 문제가있는 메서드에 대해 목록에서 currentNode를 찾아 삭제해야하지만 제대로 작동하려면 메서드를 가져올 수 없습니다. – solllodolllo

+0

deleteCurrent()가 == getIndexOfCurrnet() -> deleteByIndex (indexOfcurrent)와 같아야 함을 암시하기 위해이 코드를 게시했습니다. – hovanessyan

+0

내 프로그램을 반복하여 currentNode (또는 인덱스)를 찾을 수 없습니다. 내 프로그램에서 로컬 노드를 목록의 시작 부분에 "이전"으로 설정했습니다. 그런 다음 previous.next가 currentNode와 같지 않지만 previous (previous = previous.next.) 내 while 문 끝에서 이전과 getCurrent()를 비교하는 print 문은 true로 표시되어야하지만 그렇지 않습니다. , 그것은 내 문제가있는 곳입니다. – solllodolllo

1

당신은 당신의 코드에서 null에 지키는 것을 고려할 수 있습니다. 가정을하지 않는 것이 가장 좋습니다. 예를 들어

,

public boolean atEnd() 
{ 
    return getCurrent().getNext() == null; 

} 

더 나은이 반드시 그것을 할 수있는 가장 좋은 방법이 아니다

public boolean atEnd() 
{ 
    if (getCurrent() != null) 
    { 
    return getCurrent().getNext() == null; 
    } 
    return true; 
} 

로 기록 될 수 있습니다; 너 NoCurrentNodeException 또는 뭔가를 던질 수도 있습니다. 그것은 당신이 찾고있는 의미론에 달려 있습니다.

어느 쪽이든, NullPointerExceptions에 묻히지 않습니다.

관련 문제