我以为我有这个程序工作,但不幸的是我忽略了一些东西。如何删除第一个节点并将第二个节点转换为链表的前面。我尝试了多种方法,但最终得到相同的结果。(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;