gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:09:27 26 4
gpt4 key购买 nike

很抱歉问了一个菜鸟问题,但这里的语法有点困惑。我被要求填写将新元素插入到链接列表前面的函数。代码:

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。最后将该节点设置为新的头。

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

最佳答案

只需将新元素声明为 head 并让它指向前一个 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

关于java - 为包含数据的列表创建新头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46656295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com