链接列表删除

时间:2017-03-20 07:25:53

标签: java recursion data-structures

以下删除方法逻辑有什么问题?为什么删除后我没有得到正确的输出。

import java.util.Scanner;

//Node Class

class Node1 {

 int data;

 Node1 Next;

 Node1(int data) {

  this.data = data;

  Next = null;

 }

}

//Main Class

public class LinkedListInsert {

 //Inserting node in LinkedList

 public static Node1 insert(Node1 head, int data) {

  Node1 p = new Node1(data);

  if (head == null)

   head = p;

  else {

   Node1 start = head;

   while (start.Next != null)

    start = start.Next;

   start.Next = p;

  }

  return head;

 }

 //Deleting node from LinkedList

 public static Node1 delete(Node1 head, int d) {

  Node1 start = head;

  while (start.data != d) {

   start = start.Next;

  }

  while (start.Next != null) {

   start.data = start.Next.data;

   start = start.Next;

  }

  start = null;

  return head;

 }

 //Displaying Linked List

 public static void display(Node1 head) {

  Node1 start = head;

  while (start != null) {

   System.out.print(start.data + " ");

   start = start.Next;

  }

 }

 public static void main(String[] args) {

  // TODO Auto-generated method stub

  Scanner sc = new Scanner(System.in);

  int n;

  Node1 head = null;

  System.out.println("Enter the numbers of node to be inserted");

  n = sc.nextInt();

  while (n--> 0) {

   System.out.println("enter node");

   head = insert(head, sc.nextInt());

  }

  System.out.println("Before Deletion");

  display(head);

  delete(head, 3);//I have hard coded the deleting node as 3

  System.out.println();

  System.out.println("After Deletion");

  display(head);

 }

}

输入: 6 2 3 1 8

要删除的节点:3

输出:

删除前

6 2 3 1 8

删除后

6 2 1 8 8

正如您所看到的,节点3已从列表中删除,但是8将进入2次。 //我已将删除节点硬编码为3

3 个答案:

答案 0 :(得分:1)

由于delete()中存在错误,您实际上并没有删除任何节点,因此您只更改了要删除的节点的值以及所有节点'值到下一个节点。这是一个修改过的代码,你可以使用delete2()来测试:

whoami

答案 1 :(得分:0)

可以使用下面的代码显示链表的值。

public void display(){
        LinkedNode currNode =head;
        while(true){
            if(currNode == null){
                break;
            }
            System.out.println("Iterating a LinkedList=-=-=-=>"+currNode.val);
            currNode = currNode.nxt;
        }
    }

答案 2 :(得分:0)

请正确格式化源代码。

我刚刚浏览了您提供的代码。在删除之前,您首先插入节点,然后删除。当然,该列表还会显示当您询问“输入节点”时通过插入添加的内容。

请验证相同。

我刚试过同样的事。一旦我给出了输入 6 2 3 1 8

然后它要求进入节点,我添加了9 我再次添加了0

然后我得到了以下输出:

删除前 2 3 1 8 9 0 删除后 2 1 8 9 0 0

因此它从LinkedList中删除了6。

相关问题