单个链表中头尾插入之间的区别

时间:2019-10-27 17:49:37

标签: java linked-list

我试图了解尾部插入物(下面的代码)和头部插入物之间的区别。是我们分配下一个节点的顺序吗?

鉴于:13、15、18、20。

插入尾巴:13-> 15-> 18-> 20

头插入:20-> 18-> 15-> 13吗?

public class MylinkedList
{
  // Initialize head node
  private MyNode head;

  // Node creation
  public void tailInsert(int data)
  {
    if(head == null)
    {
      head = new MyNode(data);
      return;
    }

    // While .next of head != null then we set the lastNode to the .next
    MyNode lastNode = head;
    // Find the last node in the list and set it to lastNode
    while(lastNode.next != null)
    {
      lastNode = lastNode.next;
    }

    lastNode.next = new MyNode(data);
  }

public class MyNode
{
  public int data;
  public MyNode next;

  MyNode(data)
  {
    this.data = data
    this.next = null;
  }
}

1 个答案:

答案 0 :(得分:0)

区别在于名称。

“尾部插入”将新对象插入列表的 tail 中,因此列表的顺序与添加元素的顺序相同。

“头插入”将新对象插入列表的中,因此与添加元素的顺序相比,列表的顺序相反。

“ Head”是列表中“ frontend”的同义词; “ tail”是列表“后端”的同义词。想想一群人在等公交车;这通常是插入尾巴的情况,至少在人们礼貌的地方。线路的负责人首先到达,然后首先乘坐公共汽车。