【问题标题】:Linked list - Inserting a node before the current node链表 - 在当前节点之前插入一个节点
【发布时间】:2011-12-23 17:35:37
【问题描述】:

我正在尝试一种方法,该方法将在链表中的当前节点之前插入传递给它的节点。它有3个条件。对于这个实现,不能有任何头节点(只有对列表中第一个节点的引用),我不能再添加任何变量。

  1. 如果列表为空,则将传递的节点设置为列表中的第一个节点。
  2. 如果当前节点位于列表的前面。如果是,则将传递的节点的 next 设置为当前节点,并将第一个节点设置为传递的节点,将其移到最前面。
  3. 如果列表不为空且当前不在最前面,则遍历列表直到本地节点等于列表的当前节点。然后我执行与 2 中相同的指令。

这是我的代码。

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

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(getCurrent());

}

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()
{
    Object nData;
    Node previous; 
    Node current;
    previous = getListPtr();
    current = getListPtr();
    nData = getCurrent().getData();

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

    else if (previous == getCurrent())
    {
        getListPtr().setNext(getCurrent().getNext());
        setCurrent(getCurrent().getNext());
        nodeCount = nodeCount - 1;
    }

    else 
    {
        while (previous.getNext() != getCurrent())
        {
            previous = current;
            current = current.getNext();


        }
    previous.setNext(getCurrent().getNext());
    setCurrent(getCurrent().getNext());
    nodeCount = nodeCount - 1;  
    }
    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 = getCurrent();
    //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 = getCurrent();
            //System.out.println(nodeCount);
            nodeString = ("List contains " + nodeCount + " nodes");
            while (sNode != null)
            {
                nodeString = nodeString + " " +sNode.getData();
                sNode = sNode.getNext();
            }   
            return nodeString;
        }
    }

 }

它适用于我的 [1] 和 [2] 条件。但是我的 [3](测试 insertBeforeCurrentNode())工作不正常。我已经设置了打印语句,并且我确定我的电流在某处被重置,但我无法弄清楚在哪里可以使用一些指导或解决方案。

[1] 和 [2] 的输出是正确的。 [3] 的输出应为

[3] 列表包含 26 个节点:z x v t r p n l j h f d b c e g i k m o q s u w y a

提前感谢您的帮助。

【问题讨论】:

  • 当你说“我的电流在某处被重置”时,你是指名为current的局部变量还是名为currentNode的字段。另外:让你的变量更容易区分通常是个好主意。特别是,您的 current 变量更像是“以前的候选”而不是“当前”。
  • 我的意思是我的电流被重置了。在方法结束时,我的currentNode除了Z之外的所有条目,我认为一旦找到问题就会解决。

标签: java insert linked-list singly-linked-list


【解决方案1】:

在您的toString 方法中,您从currentNode 开始打印节点,直到列表末尾。因为您在打印结果之前调用了test.last(),所以 currentNode 将指向列表的最后一个节点,而您的 toString() 将只打印“a”。

在您的 toString() 方法中,您可能想要更改

sNode = getCurrent();

sNode = getListPtr();

打印你的 26 个节点。

【讨论】:

  • 这就像一个魅力。猜猜我的方法效果很好,我所需要的只是对简单的东西有另一双眼睛。谢谢!我很感激。
  • @user - 一个人只需要另一双眼睛就能看到简单的东西是非常普遍的。
【解决方案2】:

对于 [3],您需要保留指向两个节点的指针:一个指针位于“当前”节点中,即您要查找的节点,另一个位于“前一个”节点中,即当前节点之前的那个。这样,当您在“当前”位置找到您正在查看的节点时,您可以在“上一个”之后和“当前”之前连接新节点。在伪代码中,并在确保案例 [1] 和 [2] 之前已经涵盖之后:

Node previous = null;
Node current = first;
while (current != null && current.getValue() != searchedValue) {
    previous = current;
    current = current.getNext();
}
previous.setNext(newNode);
newNode.setNext(current);

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多