0

我需要帮助编写一个获取链表和数字并在其间添加一个节点的函数,因此每对都等于插入的数字。例如,

原来的 -

7 -> 10 -> 7 -> 15 -> 5 -> null

数字 - 20

新名单——

7 -> 13 -> 10 -> 10 -> 7 -> 13 -> 15 -> 5 -> 5 -> 15

在我的代码中,

而不是打开这个列表

7-->10-->7-->5-->15-->Null

进入这个

7 -> 13 -> 10 -> 10 -> 7 -> 13 -> 15 -> 5 -> 5 -> 15

我明白了

7-->5-->Null

这是我写的代码:

import java.util.*;
public class E3
{
    public static Scanner reader = new Scanner(System.in);
    public static void fillIn(Node<Integer> lst, int num)
    {
        Node<Integer> prev = lst;
        Node<Integer> next = lst.getNext();
        Node<Integer> fill = new Node<Integer>();
        while(lst.hasNext())
        {
            fill.setValue(num - prev.getValue());
            fill.setNext(prev.getNext());
            prev.setNext(fill);
            prev = next;
            if(next.getNext() == null)
            {
                fill.setValue(num - next.getValue());
                fill.setNext(null);
                prev.setNext(fill);
                return;
            }
            next = next.getNext();
        }
    }
    public static void main (String[] args)
    {
        Node<Integer> n = new Node<Integer>(15);
        Node<Integer> n1 = new Node<Integer>(5, n);
        Node<Integer> n2 = new Node<Integer>(7, n1);
        Node<Integer> n3 = new Node<Integer>(10, n2);
        Node<Integer> n4 = new Node<Integer>(7, n3);
        System.out.println(n4);
        fillIn(n4, 20);
        System.out.println(n4);
    }
}

谢谢!

4

0 回答 0