在目标整数之前添加一个新整数?

时间:2017-01-30 01:16:57

标签: java linked-list

我目前正在编写一个代码,允许我在指定的目标整数之前将一个元素添加到链表中,这是我到目前为止所做的。

package node;

public class IntNode {

    public int data;
    public IntNode next;
    public IntNode(int data, IntNode next) {
        this.data = data; this.next = next;
    }
    public String toString() {
        return data + "";
    }


    public static IntNode addBefore(IntNode front, int target, int newItem) {
        IntNode ptr = front;
        while(ptr != null)
        {

            if(ptr.data == target)
            {
                IntNode temp = new IntNode(newItem, ptr.next);
                ptr.next = temp;
            }
            ptr = ptr.next;
        }
        return front;

    }

    public static void main(String[] args) {
        IntNode L = null; //handle for the beginning of the LL
        L = new IntNode(19, null);
        IntNode temp = new IntNode(17, L);
        L = temp;
        addBefore(L, 17, 20);
        traverse(L);
    }

        public static void traverse(IntNode front){
            IntNode ptr = front; //ptr points to the first node of the LL

            while(ptr != null){
                System.out.print(ptr.data + " -> ");
                ptr = ptr.next;

        }  
        System.out.println("//");
        }
    }

当然,不是在目标之前添加,而是在之后添加新节点temp。有没有办法反转指针的方向,以便它可以移动到指向目标整数之前的空间?

2 个答案:

答案 0 :(得分:0)

使用第二个指针,让它说prev指向ptr之前的节点,这样一旦找到目标节点,就可以添加新指针prev之后的节点,新节点的next字段指向ptr。但是,您必须注意的特殊情况是目标是列表的头部。在这种情况下,您必须使新节点成为列表的新头。这是它应该是什么样子,

public static IntNode addBefore(IntNode front, int target, int newItem) {
    IntNode prev = null;
    IntNode ptr = front;
    while(ptr != null)
    {
        if(ptr.data == target)
        {
            if(prev == null)
            {
                front = new IntNode(newItem, front);
            }
            else
            {
                prev.next = new IntNode(newItem, ptr);
            }
            break;
        }
        prev = ptr;
        ptr = ptr.next;
    }

    return front;
}

答案 1 :(得分:0)

如何修改当前节点的数据?

public static IntNode addBefore(IntNode front, int target, int newItem) {
    if (front.data == target) {
        IntNode currentFront = new IntNode(front.data, front.next);
        front.data = newItem;
        front.next = currentFront;
    } else {
        return addBefore(front.next, target, newItem);
    }
    return front;
}

您:

public static void main(String[] args) {
    IntNode L = null; //handle for the beginning of the LL
    L = new IntNode(19, null);
    IntNode temp = new IntNode(17, L);
    L = temp;
    traverse(L);
    addBefore(L, 17, 20);
    traverse(L);
}

给了我:

17 -> 19 -> //
20 -> 17 -> 19 -> //

另一次尝试:

traverse(L);
addBefore(L, 19, 20);
traverse(L);

给出:

17 -> 19 -> //
17 -> 20 -> 19 -> //