【问题标题】:Two part, Removing last element and replacing two elements in node in Java两部分,在Java中删除最后一个元素并替换节点中的两个元素
【发布时间】:2023-03-16 05:08:01
【问题描述】:

我正在处理我的作业中的链表,一部分是从列表中删除最后一个元素,另一部分是用链表中的新元素替换一个元素。

我实际上很难弄清楚如何将它组合在一起,我对删除和替换进行了一些研究,结果并没有真正的帮助,但有一个与替换密切相关。

 public boolean replace(int element, int index) {
        Node cursor = first;
        Node prev = null;

        while (cursor != null && index >= 0) {
            index--;
            prev = cursor;
            cursor = cursor.next;
        }

        if (index > 0) return false;

        if (prev != null)
            prev.element = element;

        return true;
    }

但我的任务是不使用布尔值,而是使用public void replace(int oldVal, int newVal)

关于替换的另一部分是这样的

/*********************************
// public void replace(int oldVal, int newVal)
// —replaces all occurrences of oldVal in the list with newVal.
//********************************

    public void replace(int oldVal, int newVal)
    {
          IntNode oldval = new IntNode(oldVal,front);
        IntNode newval = new IntNode(newVal,front);

        if (front == null)
        {
            front = newval;
        }
        else
            while (oldval.next != null)
            {
                oldval = oldval.next;
                oldval.next = newval;
            }

    }

已更新,如果代码正确以允许我用链表中的新元素更改一个元素,仍然在苦苦挣扎。

 public IntNode(int val, IntNode next)
       {
           this.val = val;
           this.next = next;
       }

除非我弄错了并且我不需要使用它。

结果应该允许我从列表末尾删除一个元素,并能够用新值替换旧值。

【问题讨论】:

  • 能否展示调用 removeLast() 的代码以及 front 和 count 是如何定义的?
  • 确定java public static void dispatch(int choice) { int newVal; switch(choice) { .... case 7: //remove the last element list.removeLast(); break;
  • 前面和计数被定义java public class IntList { private IntNode front; //first node in list private int count; //count all elements

标签: java replace linked-list nodes


【解决方案1】:

假设您的节点的 .next 工作正常,您的 removeLast 应该如下所示:

public void removeLast()
{
    if (front != null && front.next != null)
    {
        IntNode secondtolast = front;
        while (secondtolast.next.next != null)
        {
            secondtolast = secondtolast.next;
        }
        secondtolast.next = null;
    }
}

根据您的 replace() 函数的描述,您不会替换节点,而是替换节点的值。

public void replace(int oldVal, int newVal)
{
    while (front.next != null)
    {
        if (front.val == oldVal)
        {
            front.val = newVal;
        }
        front = front.next;
    } 
}

【讨论】:

  • 所以我需要确保 front 和 front.next 都不为空,以确保我会查看最后一个元素并将其删除?
  • 如果 front 为空,则列表中没有任何内容。如果 front.next 为 null,则 front 是列表中的第一个和最后一个。在这种情况下,根据您的规格,您可能希望也可能不希望移除前端。
  • 我测试了它,现在我明白了,谢谢你:D 现在我还有一个部分才能上交:P 我更新了我的代码,但我不确定它是否正确
  • 我的代码几乎与此非常相似,我正在测试我拥有的内容并与您推荐的内容进行比较。但再次感谢 L:D
猜你喜欢
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 2021-02-23
  • 2017-04-09
  • 2022-10-01
  • 2021-08-10
相关资源
最近更新 更多