英文:
What is the difference between two methods of creation linked list in java?
问题
push() 方法和 add() 方法有什么区别,因为它们都是通过构造函数将值推入链表,但 add() 不会添加该值。
void push(Node node){
Node newnode = node;
newnode.next = head;
head = newnode;
}
void add(Node node, Node head){
addNode(node, head);
}
void addNode(Node node, Node head){
Node newnode = node;
newnode.next = head;
head = newnode;
}
在这里,push() 方法将新节点添加到链表的头部,使其成为新的头节点。而 add() 方法实际上只是将新节点添加到链表的头部,与 push() 方法执行相同的操作,没有区别。
英文:
what the difference between methods push() and add() since this ones do the same stuff - push the value into linked list via constructor, but add() doesn't add the value
public class LinkedList {
static class Node {
int value;
Node next;
Node(int value){
this.value = value;
next = null; }
};
Node head;
Node next;
void push(Node node){
Node newnode = node;
newnode.next = head;
head = newnode; }
void add(Node node, Node head){addNode(node,head);}
void addNode(Node node, Node head){
Node newnode = node;
newnode.next = head;
head = newnode; }
/* Function to print linked list */
void printlist(Node head){
while(head != null){
System.out.println(head.value + " ");
head = head.next; }
}
// Driver program to test above functions
public static void main(String args[])
{
LinkedList list = new LinkedList();
list.head = null;
list.head = new Node(5);
list.push(new Node(6));
list.add(new Node(3), list.head);
list.push(new Node(7));
list.printlist(list.head);
}
}
答案1
得分: 1
您的_add_方法,或者更正确地说,_addNode_方法,没有对实例进行任何操作。
实际上,它将参数_head_分配给参数_node_的_next_值。
void addNode(Node node, Node head) {
node.next = head;
}
_push_方法是正确的,它将对象堆叠在实例的_head_节点之前。
您可以删除_addNode_方法,对于_add_方法,它只需要1个参数。
您需要定位结构中的最后一个节点,然后将参数追加到它。
void add(Node node) {
Node lastNode = this.head;
while (lastNode.next != null) lastNode = lastNode.next;
lastNode.next = node;
}
英文:
Your add method, or more correctly, addNode method, is not doing anything to the instance.
It is effectively assigning the parameter head to, the next value of parameter, node.
void addNode(Node node, Node head) {
node.next = head;
}
The push method is correct, it will stack the object before the instance's head node.
You can remove the the addNode method, and for the add method, it only requires 1 parameter.
You'll want to locate the last node in the structure, and then append the parameter to it.
void add(Node node) {
Node lastNode = this.head;
while (lastNode.next != null) lastNode = lastNode.next;
lastNode.next = node;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论