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;
}