[英]Creating linked lists in java without using in-built methods/importing util
The question is to create a linked list that creates nodes and links them and should have the following methods.
问题是创建一个链表,该链表创建节点并将其链接起来,并应具有以下方法。
- AddFirst
AddFirst
- AddLast
最后添加
- Remove/Delete
删除/删除
- Insert before and after...
插入之前和之后...
I've managed to do the bit below but I can't seem to get what's wrong with the code. 我已经设法做到以下几点,但是我似乎无法理解代码的问题。 Piece of the error reads " LinkedList.java [line: 16] Error: variable head might not have been initialized "
错误内容为“ LinkedList.java [line:16]错误:变量头可能尚未初始化”
/*Uses the node class to create a linked list of integer type
* nodes and stores them
*/
public class LinkedList
{
public Node head;
public static void main(String [] args) {
}
//Methods adds a link to the head
//Appends to the beginning of the list
public void addFirst(int data) {
Node head = new Node(data, head);
//Because head is the pointer to the first node
// Traversing the list
Node temp = head;
while (temp != null) {
temp = temp.next;
}
}
//Adding at the end of the list
public void addLast(int data) {
if (head == null) {
addFirst(data);
//When the list is empty, i.e, head points to null
} else {//When list is populated
Node temp = head;
while (temp.next != null) {
temp = temp.next;
temp.next = new Node(data, null);
}
}
}
//To insert a new node after a given "key"
//_data is the new node data
public void insAft(int _data, int key) {
Node temp = head;
while (temp != null && temp.data != key) {
temp = temp.next;
}
if (temp != null) {
temp.next = new Node(_data, temp.next);
}
}
}
/*Node class to create the node (object)
* takes integer parameters
*/
class Node{
public int data;
Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public String toString() {
return data + " ";
}
}
The variable head
that is giving you the error ( new Node(data,
head)
) refers to the new variable head
that you are in the process of creating. 给您错误的变量
head
( new Node(data,
head)
)是指您正在创建的新变量head
。 This error can be solved by adding this
: 可以通过添加
this
解决此错误:
Node head = new Node(data, this.head);
Or, if you're not trying to create a new variable: 或者,如果您不尝试创建新变量:
head = new Node(data, head);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.