연결리스트의 핵심 주어진 노드를 삭제

user9179677 :

나는 주어진 키 연결리스트에서 노드를 삭제하는 코드를 작성했습니다. 내 목록을 여기에 첫 번째 노드를 삭제하려고하고 통과 그러나, 여전히 이전에 존재하는 첫 번째 노드를 보이고있다. 누군가가 내가 여기 잘못 뭐하는 거지 말씀해 주시겠습니까? 클래스 이름으로 시작하는 내 전체 코드

public class LinkedList {
    //removing Node nested class





    public void buildList1() {
        head=new Node(1);
        head.next=new Node(3);
        head.next.next=new Node(5);
        head.next.next.next=new Node(7);


    }

    public boolean removeNode(Node head,int x) {
        //1 3 5 7---to delete 5
        Node q=head;//q
    //  Node p=head.next;//p
        Node prev=null;

        if(q!=null && q.data==x) {
            head=q.next;
            //q=null;
            System.out.println("next to head" + head.data);
            return true;
        }
        while(q!=null && q.data!=x) {
            prev=q;
            q=q.next;
        }
        if(q==null)
            return false;
        prev.next=q.next;

        return true;

    }

    public void printList() 
    { 
        Node tnode = head; 
        while (tnode != null) 
        { 
            System.out.print(tnode.data+" "); 
            tnode = tnode.next; 
        } 
    } 

    public static void main(String args[]) {
        LinkedList list=new LinkedList();
        list.buildList1();


        list.printList();
        System.out.println(list.removeNode(list.head, 1));
        list.printList();

    }

}
P11 :

@JD D 좋은 대답을했다,하지만 난 할 것이 removeNode훨씬 더 쉽게 방법을.

public boolean removeNode(int x) {
    tempNode = this.head;
    prevNode = null;
    if (this.head != null && this.head.data == x) {
        this.head = this.head.next;
        return true;
    }
    while (tempNode != null) {
        if (tempNode.data == x) {
            prevNode.next = tempNode.next;
            return true;
        }
        prevNode = tempNode;
        tempNode = tempNode.next;
    }
    return false;
}

추천

출처http://43.154.161.224:23101/article/api/json?id=210771&siteId=1