gpt4 book ai didi

java - 在链表中添加节点

转载 作者:行者123 更新时间:2023-12-01 13:29:53 24 4
gpt4 key购买 nike

尝试在下面的程序中实现single-linked-list,我真的无法理解如何在链接列表中添加节点(首先,我尝试在空链接列表)。

简单来说,我尝试 setDatasetNextgetSizeofList() 每次都返回 0 ....现在对我来说真的看起来像火箭科学!!

问题:有人可以告诉我如何实现它......或者更确切地说,向现有链表添加一个节点......

到目前为止我所尝试过的以及为什么它们不起作用:我引用了多个程序,但它们对我来说太复杂而无法理解(火箭科学),所以写道下面的程序是我从算法中理解的……但即使在算法中,它们也只是展示了如何实现的方法,这就是我失败的地方,因为我不明白什么是数据类型和添加节点时要传递 value...


请注意,我不是java人,所以请放轻松,这个问题是为了学习而提出的

package Data_S;

public class Linked_List {

private int data;
private Linked_List next_ptr;
private Linked_List headNode = null;

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Linked_List ll = new Linked_List();
//ll.setnext(25);
ll.insert_node(24);
ll.traverse();
ll.getSizeofList();
}


//size of list
public void getSizeofList()
{
int l = 0;
Linked_List curr = headNode;
while(curr != null)
{
l++;
curr = curr.getnext();
}
System.out.print("Size of list is = "+l);
}

//insert node
public void insert_node(/*Linked_List node, */int data)
{
if(headNode == null)
{
System.out.println("in insert"); // checking
this.setnext(headNode);
this.setData(data);
System.out.print("value = "+this.getData());
}
}

//set data for this node
public void setData(int data)
{
this.data = data;
}

//return the data
public int getData()
{
return this.data;
}

//set next pointer
public void setnext(Linked_List next_ptr)
{
this.next_ptr = next_ptr;
}

//get next pointer
public Linked_List getnext()
{
return this.next_ptr;
}


}

最佳答案

您必须区分链表的单个链(节点)和整个容器(LinkedList)。

public class LinkedList {
Node head;
int size; // Maybe

public void insertAtEnd(int data) {
Node previous = null;
for (Node current = head; current != null; current = current.next) {
previous = current;
}
Node baby = new Node(data);
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}

public void insertInSortedList(int data) {
Node previous = null;
Node current = null;
for (current = head; current != null && data < current.data;
current = current.next) {
previous = current;
}
Node baby = new Node(data);
baby.next = current;
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}
}

class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}

有时人们可能会将封装视为:

public class LinkedList {
private static class Node {
}
...
}

关于java - 在链表中添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632621/

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