为包含数据的列表创建新头

时间:2017-10-09 23:07:22

标签: java linked-list

对于noob问题很抱歉,但这里的语法有点令人困惑。我被要求填写函数以将新元素插入到链表的前面。代码:

class LinkedList
{
    public LinkedList ()
    {
        this.head = null;
    }

    /* returns true, if the list is empty, else false */
    public boolean isEmpty ()
    {
        return head == null;
    }

    /* returns the first element of the list, assuming that the list is not empty */
    public int front ()
    {
        return head.data;
    }

    /* prints the list */
    public void print ()
    {
        System.out.print("(");
        for (ListNode i = head; i != null; i = i.next)
            System.out.print(i.data + " ");
        System.out.println(")");
    }

    /* inserts x into the beginning of the list */
    public void insertFront (int x)
    {
        /* FILL HERE!!! */
    }
}

节点的代码:

class ListNode
{
    public ListNode()
    {
        this.data = 0;
        this.next = null;
    }

    public int data;
    public ListNode next;
}

我想我需要创建一个新节点,为下一个运算符分配当前头的值,并将值设置为x。然后最终将节点设置为新头。

有人可以告诉我如何执行这些基本命令。

1 个答案:

答案 0 :(得分:1)

只需将您的新元素声明为head,然后让它指向前一个头部,现在是第二个元素。

/* inserts x into the beginning of the list */
public void insertFront(int x)
{
    // Temporarily memorize previous head
    ListNode previousHead = this.head;

    // Create the new head element
    ListNode nextHead = new ListNode();
    nextHead.data = x;
    // Let it point to the previous element which is now the second element
    nextHead.next = previousHead;

    // Update the head reference to the new head
    this.head = nextHead;
}

以下是该过程的一个小例子:

LinkedList structure, inserting at front