...

/

Solution Review: Construct a Double-Linked List

Solution Review: Construct a Double-Linked List

This lesson discusses the solution to the challenge given in the previous lesson.

We'll cover the following...
Press + to interact
package main
import (
"container/list"
"fmt"
)
func insertListElements(n int)(*list.List){ // add elements in list from 1 to n
lst := list.New()
for i:=1;i<=n;i++{
lst.PushBack(i) // insertion here
}
return lst
}
func main() {
n := 5 // total number of elements to be inserted
myList := insertListElements(n) // function call
for e := myList.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value) // printing values of list
}
}

In the code above, at line 4, we import a package container/list because it is used for the implementation of doubly-linked lists. Look at the header of function insertListElements at line 8: func insertListElements(n int)(*list.List). This function takes a parameter n and is returning a double-linked list. At line 9, we are making a new but empty doubly-linked list lst using list.New() function. Now we have a for loop that will run n times. The ...