java-删除链表中指定键的节点

前端之家收集整理的这篇文章主要介绍了java-删除链表中指定键的节点 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我已经编写了代码,从给定密钥的链表中删除了一个节点.但是,当我尝试删除此处的第一个节点然后遍历列表时,它仍显示先前存在的第一个节点.有人可以告诉我我在做什么错吗?我的整个代码都以类名开头

  1. public class LinkedList {
  2. //removing Node nested class
  3. public void buildList1() {
  4. head=new Node(1);
  5. head.next=new Node(3);
  6. head.next.next=new Node(5);
  7. head.next.next.next=new Node(7);
  8. }
  9. public boolean removeNode(Node head,int x) {
  10. //1 3 5 7---to delete 5
  11. Node q=head;//q
  12. // Node p=head.next;//p
  13. Node prev=null;
  14. if(q!=null && q.data==x) {
  15. head=q.next;
  16. //q=null;
  17. System.out.println("next to head" + head.data);
  18. return true;
  19. }
  20. while(q!=null && q.data!=x) {
  21. prev=q;
  22. q=q.next;
  23. }
  24. if(q==null)
  25. return false;
  26. prev.next=q.next;
  27. return true;
  28. }
  29. public void printList()
  30. {
  31. Node tnode = head;
  32. while (tnode != null)
  33. {
  34. System.out.print(tnode.data+" ");
  35. tnode = tnode.next;
  36. }
  37. }
  38. public static void main(String args[]) {
  39. LinkedList list=new LinkedList();
  40. list.buildList1();
  41. list.printList();
  42. System.out.println(list.removeNode(list.head,1));
  43. list.printList();
  44. }
  45. }
最佳答案
@JD D有一个很好的答案,但我会更轻松地执行removeNode方法.

  1. public boolean removeNode(int x) {
  2. tempNode = this.head;
  3. prevNode = null;
  4. if (this.head != null && this.head.data == x) {
  5. this.head = this.head.next;
  6. return true;
  7. }
  8. while (tempNode != null) {
  9. if (tempNode.data == x) {
  10. prevNode.next = tempNode.next;
  11. return true;
  12. }
  13. prevNode = tempNode;
  14. tempNode = tempNode.next;
  15. }
  16. return false;
  17. }

猜你在找的Java相关文章