How to implement a single linked list with Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

First, Concept introduction

The following diagram is our single-linked list of the coal fleet.

Each coal truck is a single-link element, and the coals in each compartment are the data stored in the element. The front and rear of the car through the chain, as a single-linked list of coal cars, starting from 1th, each car is known to pull the back of the car, but do not know the front is which car pulled their own. The first compartment does not have any carriages to pull it, we call it the front, the fifth carriage behind the other carriages, we call the rear.

As a single-linked list, its biggest feature is the ability to arbitrarily increase the length of the fleet, but also to reduce the length of the team. This is the biggest advantage than the array bus.

Second, go language implementation explained

1. Node

Each compartment is made up of bodywork, ropes and coal. In the Go language, the type of the custom composition is the structure, of course, for versatility, we have to convert the compartment into a node, the element, the coal into the data, the rope into the pointer.

Type Node struct {    data Object    next *node}

Use a graph to describe this correspondence relationship.

Here the struct node represents the compartment, data indicates that the coal is of type object, and next is the rope holding the next compartment, indicated by a pointer.

For the carriage, in addition to coal, but also to put fruits, clothing, food and so on, so the type of data here must be universal, of course, there is no Java object type in go, so we define a.

Type Object interface{}

2. Linked list

It is not enough to have carriages, and we have to describe the fleet of carriages. Each single-linked list fleet has a front, tail and number of carriages, which we also perform in the same structure.

type List struct {    size UInt64//number of vehicles     head *node  //Headlights     tail *node  Car tail }

3. Methods

(1) initialization

The first step is to assemble a single-linked list of fleets, which is the initialization. But at first the team was a shell, not a compartment.

func (List *list) Init () {    (*list). Size = 0/    /The list is empty at this time     (*list). Head = nil  //No headlights 
    (*list). Tail = nil //No car tail}

(2) Adding elements

The current single-linked list is empty, so we're going to add elements to it.

func (List *list) Append (node *node) {    (*list). Head = node//This is the first element of a single-linked list and the head     of a linked list (*list). Tail = node//is also the tail of the single-linked list     (*list). Size = 1    //single-linked list with first element }

Now that the single-linked list has the first element, I want to add another element, of course, to the tail of the single-linked list.

func (List *list) Append (node *node) {    if (*list). Size = = 0 {//no element added        (*list). Head = node//This is a single chain The first element of the table is also the head of the list         (*list). Tail = node//is also the tail of the single-linked list        (*list). Size = 1//    the single-linked list has the first element    } else {//has an element and then adds the c8>        Oldtail: = (*list). Tail        (*oldtail). Next = node  //node is placed behind the trailing element         (*list). Tail = node     /node becomes the new tail         (*list). size++          //Increased number of elements     }}

Analysis of the above code there are 3 points of doubt, Yuan Fang you how to think? Subordinates think
First, if node is empty, then add no meaning;
Second, there are duplicates in the code;
This third, vulgar job how to know the new results?
The following brother David followed Yuan Fang's ideas to improve the code.

func (List *list) Append (node *node) bool {    if node = = Nil {        return false    }        (*node). Next = Ni L    //put new elements into the single-linked list    if (*list). Size = = 0 {         (*list). Head = Node      } else {         oldtail: = (*list). Tail        (*o Ldtail). Next = node      }/    /Adjust the trailing position, and the number of linked list elements    (*list). Tail = node/node becomes the new tail      (*list). size++      // Increase in number of elements    return true}

(3) Inserting elements

One day the leader let David brother put his brother-to the first, so David Brother in order to make a good leader horse fart. I racked my brains to get a way.

Func (list *list) Insert (node *node) bool {    if node = = Nil {        return false    }     (*node). Next = (*list). Hea D   //leader brother-to the front first    (*list). Head = node           //leader brother-becomes first    (*list). size++    return True}

To support relations in the queue of more and more people, the leadership of the connections can not move, can only plug in the back of the team. Davido then changed the code, adding the positional parameters.

Func (list *list) insert (i uint,node *node) bool {    //null node, index out of range, and empty list cannot be inserted    if node = nil | | i > (*list). siz e | | (*list). Size = = 0 {        return false    }    If i = = 0 {//Direct row first, also lead brother-can        (*node). Next = (*list). Head        (*list) . Head = Node    } else {        //Find Previous element        Preitem: = (*list). Head for        J: = 1; J < I; J + + {//Count front I element            PR Eitem = (*preitem). Next        }        //The original element is placed after the new element, and the new element is placed behind the previous element        (*node). Next = (*preitem). Next        (*preitem) . Next = Preitem    }        (*list). size++         return True}

(4) Deleting an element

Queue connections too many, affecting the normal queue of people, was complained, Davido had to find a way to delete some.

Func (list *list) Remove (i uint, node *node) bool {    If I >= (*list). Size {        return false    }        If i = = 0 {/ /delete Head        node = (*list). Head        (*list). Head = (*node). Next if        (*list). Size = = 1 {//If there is only one element, the tail is also adjusted            (*list) . Tail = nil        }    } else {        Preitem: = (*list). Head for        J: = 1; J < I; J + + {            Preitem = (*preitem). NE XT        }            node = (*preitem). Next        (*preitem). Next = (*node). Next        if i = = ((*list). size-1) {//delete trailing, trailing pointer Need to adjust            (*list). Tail = Preitem        }    }    (*list). size--    return True}

(5) Get

In order to get the elements of a location, we need a method.

Func (list *list) Get (i uint) *node {    If I >= (*list). Size {        return nil    }    Item: = (*list). head
   
    for J: = 0; J < I; J + + {    //from head number I        item = (*item). Next    }    return Item}
   

The basic framework has come out, but there are still a few interfaces that have not yet been implemented as homework after class.

Third, summary

A single-linked list is similar to a train, one after the other, so this section introduces the implementation of the single-linked list's go language from the train analogy. In the Interface implementation section Davido the ordinal as the Operation keyword for each node in the linked list. In practice, we tend to use one of the fields in data as the Operation keyword. So this also derives from the different interfaces of the linked list, and you can refer to the code implementation in the link that David left as an understanding. At the same time some implementations separate the header from the data, which simplifies the implementation of the code to some extent.

Code download

Iv. Exercises

(1) Definition and realization of complement Getsize,removeall,gethead and GetTail.
(2) Taking data as parameter, consider the realization of single-linked list.
(3) The head of the single linked list is independent, at this time the head is independent, do not store data, for example, consider the implementation of a single-linked list, and compare this implementation.

(4) If the head and tail are independent, do not store data, at this time the single-linked list how to implement? Is it easier to implement code when inserting a delete operation?

582 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.