添加到链表的前面 [英] 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 {
public Node next;
private String _val;
public Node(String val) {
_val = val;
}
}
这篇关于添加到链表的前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文