【发布时间】:2016-12-17 10:22:31
【问题描述】:
//我有一个Node.java类
public class Node{
int data;
Node next;
public Node(int d) {
data = d;
}
}
//还有一个java类
class LinkedList {
Node head;
public static void main(String[] args) {
LinkedList list = new LinkedList();
//Executing this loop
for (int i = 0; i < 5; i++) {
**list.add(i);**
}
}
void add(int value){
Node newNode = new Node(value);
if(head == null )//Very first time its create the head object when i = 0
{
head = newNode;
}else if(head.next == null){//This is for when i value is 1
head.next = newNode;
}else{ //else part execute i >= 2
//Created new node with head.next which mean value 1.And head is 0
Node temp = head.next;
// Just need this object initialization for reference
Node temp1 = newNode;
//Checking head.next is null or not if its null skip this loop execution
while(temp != null)
{
temp1 = temp;
temp = temp.next;
}
// Here we set newNode.next to null
newNode.next = temp1.next;
temp1.next = newNode;
}
}
}
我的问题在这里,当 temp1.next = newNode;行执行头对象已添加 下一个值。
** //例如 if head = 0,head.next = 1 when temp1.next = newNode;行执行 head.next.next = 2 正在添加头部。当我们没有头对象引用时它是如何发生的。
【问题讨论】:
-
请花点时间正确格式化您的问题。
-
说真的:您希望我们帮助您;所以请您花一些时间来正确格式化您的问题。适当的缩进、格式化等。您知道,创建问题时会有一个预览。
标签: java list data-structures singly-linked-list