【问题标题】:copying items from one single linked list to another将项目从一个链表复制到另一个链表
【发布时间】:2017-05-31 00:00:54
【问题描述】:

我刚开始学习链表,需要有关这段代码的帮助。我需要编写一种方法,将所有项目从一个链表复制到另一个链表。 任何帮助,将不胜感激。谢谢。

public static ListNode copy(ListNode list){
    //code
} 

【问题讨论】:

  • 到目前为止你尝试过什么?另外,ListNode 是什么?
  • 你显然没有用谷歌搜索,因为 Arrays.copyAll 很容易匹配你的搜索。
  • 如果您知道如何将项目添加到链表,以及如何遍历链表的所有项目,那么您就知道如何复制链表。那么您需要帮助完成以下哪些任务?

标签: java singly-linked-list


【解决方案1】:

只是从我的脑海中开始,但正如上面在 cmets 中提到的那样,您可能应该问更具体的问题。

class ListNode {
    int value;
    ListNode next;
    public ListNode(int value) {
        super();
        this.value = value;
    }
}

public class Test {

    public static ListNode copy(ListNode list){
        if (list == null)
            return null;

        ListNode res = new ListNode(list.value);
        ListNode resTmp = res;
        ListNode listTmp = list;

        while (listTmp.next != null){
            listTmp = listTmp.next;
            resTmp.next = new ListNode(listTmp.value);
            resTmp = resTmp.next;
        }

        return res;
    }

    public static void main(String[] args) {
        ListNode input = new ListNode(11);
        input.next = new ListNode(12);
        input.next.next = new ListNode(13);

        ListNode output = copy(input);

        while (output != null){
            System.out.println(output.value);
            output = output.next;
        }
    }

}

【讨论】:

  • 感谢您的帮助,抱歉这个问题很糟糕,这是我第一次发帖,一定会添加更多信息并包括我自己的尝试
猜你喜欢
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多