添加到链接列表的前面 [英] Add to front of linked list
本文介绍了添加到链接列表的前面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对如何添加到链表的前面感到困惑。
I am confused as to how to add to the front of the linked list.
/**
* data is added to the front of the list
* @modifies this
* @ffects 2-->4-->6 becomes data-->2-->4-->6
*/
public void insert(E data) {
if (front == null)
front = new Node(data, null);
else {
Node temp = new Node(data, front);
front = temp;
}
}
这会创建一个循环。我如何避免这种情况?
This creates a cycle. How do I avoid that?
我有一个LinkedList类,它将前端节点保存在一个名为front的变量中。
我在这个LinkedList类中有一个Node类。
I have a LinkedList class which holds the front Node, in a variable called front. I have a Node class within this LinkedList class.
任何帮助都将不胜感激。
谢谢。
Any help would be appreciated. Thank you.
推荐答案
您是否可以访问下一步节点?
Don't you have access to "Next" node ?
在这种情况下
public void insert(E data)
{
if (front == null)
{
front = new Node(data, null);
}
else
{
Node temp = new Node(data, null);
temp.next = front;
front = temp;
}
}
-
class LinkedList
{
Node front;
LinkedList() { front = null; }
public void AddToFront(String v)
{
if (front == null)
{
front = new Node(v);
}
else
{
Node n = new Node(v);
n.next = front;
front = n;
}
}
}
class Node
{
private String _val;
public Node(String val)
{
_val = val;
}
public Node next;
}
这篇关于添加到链接列表的前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文