我以为我有这个程序工作,但不幸的是我忽略了一些东西。如何删除第一个节点并将第二个节点转换为链表的前端。我尝试了很多方法,但结果都是一样的。(LinkedList保持不变)如能提供指导,我将不胜感激。
节点类public class Node {
private String data;
private Node next;
Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
主要public static void main(String[] args) {
Node list = new Node("NODE 1",new Node("NODE 2",new Node("NODE 3", null)));
list = insertSecond(list,"New Node");
list = addLast(list,"LAST NODE");
printList(list);
System.out.println();
deleteNode(list, "NODE 1");
printList(list);
}
public static Node deleteNode(Node list,String str)
{
Node temp = list;
Node prev = list;
while(temp != null)
{
if(temp.getData().equals(str))
{
if(temp.getData().equals(list.getData()))
{
list = list.getNext();
return deleteNode(list,str);
}
else
{
prev.setNext(prev.getNext().getNext());
}
}
prev = temp;
temp = temp.getNext();
}
return list;
您的deleteNode
函数应该返回新列表的头部。这只需要在你描述的一个边缘情况下——删除列表的头。
list = deleteNode(list, str);
你也不需要递归地执行deleteNode
方法,迭代节点元素应该足够了:
public static Node deleteNode(Node list, String str) {
// I'm assuming that you are deleting the first inscance of the string
Node temp = list;
Node prev = list;
while(temp != null) {
if(temp.getData().equals(str)) {
if(temp.getData().equals(list.getData())) {
return list.getNext();
}
else {
prev.setNext(temp.getNext());
return list;
}
}
prev = temp;
temp = temp.getNext();
}
return list;
}