用于在双向链表中插入的更好的方法结构(Java)

时间:2015-04-26 23:59:01

标签: java linked-list doubly-linked-list

这是我的双向链表插入方法。它工作但传递方法的两个参数似乎很麻烦。任何人都可以提出比这更清洁的方法吗?

代码             //执行示例             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;
    }


}

2 个答案:

答案 0 :(得分:2)

public void insert(Link newNode)
{
    if(head == null)
    {
        head = newNode;
        tail = newNode;
    }
    else
    {
        tail.next = newNode;
        newNode.prev = tail;
        tail = newNode;
    }

}

BTW,重命名您的课程,因为LinkedListjava.util.LinkedList

过于相似

答案 1 :(得分:1)

如果您要追加到LinkedList的末尾,则可以设置list.head.prev.next = newLinknewLink.next = list.headnewLink.prev = list.head.prevlist.head.prev = newLink