这是我的双向链表插入方法。它工作但传递方法的两个参数似乎很麻烦。任何人都可以提出比这更清洁的方法吗?
代码 //执行示例 MyLinkedList list = new MyLinkedList(); 链接link1 =新链接(“A”); list.insert(list.head,LINK1); 链接link2 =新链接(“B”); list.insert(link1,link2); 链接link3 =新链接(“C”); list.insert(link2,link3); list.display_List_Start_From_Head();
public void insert(Link currentNode, Link newNode)
{
if(head == null)
{
head = newNode;
tail = newNode;
}
else
{
currentNode.next = newNode;
newNode.prev = currentNode;
tail = newNode;
}
}
public class MyLinkedList {
public Link head;
public Link tail;
public Link currentNode;
public Link newNode;
public MyLinkedList()
{
head = null;
tail = null;
}
public class Link {
public String data;
public Link prev;
public Link next;
public Link(String data)
{
this(data,null,null);
}
public Link(String data, Link prev, Link next)
{
this.data = data;
this.prev = prev;
this.next = next;
}
}
答案 0 :(得分:2)
public void insert(Link newNode)
{
if(head == null)
{
head = newNode;
tail = newNode;
}
else
{
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
BTW,重命名您的课程,因为LinkedList
与java.util.LinkedList
答案 1 :(得分:1)
如果您要追加到LinkedList
的末尾,则可以设置list.head.prev.next = newLink
,newLink.next = list.head
,newLink.prev = list.head.prev
和list.head.prev = newLink
。