This is a creation in Article, where the information may have evolved or changed.
Description
The previous article is about sequential storage structures in linear tables, although his reading complexity is O (1), but its drawbacks are obvious, insertions and deletions need to move many elements, and a contiguous area of memory needs to be allocated
Single linked list of linear tables
A single linked list solves some of the above problems, and does not have a large contiguous area of memory, the code is as follows
The chain storage structure in the Package main//linear table//The first node is the head node and does not actually hold the data, the head node basically represents the entire list import ("FMT") type Elem inttype linknode struct {Data El EM Next *linknode}//generate head node func New () *linknode {///The following data can be used to represent the length of the list of return &linknode{0, nil}}//insert a in front of the list I position Element e, complexity of O (n) func (head *linknode) Insert (i int, e Elem) bool {p: = head J: = 1 for nil! = P && J < I {p = p.next j + +} if nil = = P | | J > I {fmt. PRINTLN ("Pls check i:", i) return false} s: = &linknode{data:e} s.next = P.next P.next = s RET Urn true}//Traverse list func (head *linknode) Traverse () {point: = head. Next for nil! = Point {fmt. Println (point. Data) point = point. Next} fmt. Println ("--------done----------")}//Delete the first node of the list, the complexity is O (n) func (head *linknode) Delete (i int) bool {p: = head J: = 1 for (nil! = P && J < i) {p = p.next j + +} if nil = = P | | J > I {fmt. PRINTLN ("Pls check i:", i) reTurn false} P.next = P.next.next return true}//Gets the first element in the list, with the complexity O (n) func (head *linknode) get (i int) Elem { P: = head. Next for j:= 1; j< i; j + + {if nil = = p {///= return error return-100001} P=p.next} return P.data}func Main () {linkedlist: = New () Linkedlist.insert (1, 9) Linkedlist.insert (1) Linkedlist.insert (1 , 999) Linkedlist.insert (1, 9999) Linkedlist.insert (1, 99999) Linkedlist.insert (1, 999999) linkedlist.traverse () Linkedlist.delete (4) Linkedlist.traverse () E: = Linkedlist.get (4) fmt. Println (E)}