简体   繁体   English

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

[英]Difference between head and tail insert in a single linkedlist

I'm trying to understand the difference between a tail insert (code below) and a head insert.我试图了解尾部插入(下面的代码)和头部插入之间的区别。 Is it the order in which we assign the next node?是我们分配下一个节点的顺序吗?

Given: 13, 15, 18, 20.给定:13、15、18、20。

Tail insert: 13 -> 15 -> 18 -> 20尾部插入:13 -> 15 -> 18 -> 20

Head insert: 20 -> 18 -> 15 -> 13?头部插入: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;
  }
}

The difference is in the names.区别在于名称。

A "tail insert" inserts the new object at the tail of the list and thus the list has the same order as the order in which elements are added. “尾部插入”在列表的尾部插入新的 object,因此列表的顺序与添加元素的顺序相同。

A "head insert" inserts the new object at the head of the list, so the list has the reverse order compared to the order in which elements are added. “头部插入”将新的 object 插入到列表的头部,因此列表的顺序与添加元素的顺序相反。

"Head" is a synonym for "front end" of the list; “头”是列表“前端”的同义词; "tail" is a synonym for the "back end" of the list. “tail”是列表“后端”的同义词。 Think about a line of people waiting for a bus;想想排队等候公共汽车的人; this is generally a case of tail insertion, at least where people are polite.这通常是插入尾巴的情况,至少在人们有礼貌的情况下。 The head of the line arrived first and gets on the bus first.线头先到,先上车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM