definition of linked list:
type ListNode struct {
Val int
Next *ListNode
}
insert helper that does the pointer manipulation: I am aware that root.Val == 0 is does not solve problems where the input array contains 0 elements, so please suggest a more general approach to solve this.
func insert(root *ListNode, elem int) *ListNode {
temp := ListNode{Val: elem, Next: nil}
if root.Val == 0 {
root = &temp
} else {
curr := root
for curr.Next != nil {
curr = curr.Next
}
curr = &temp
}
return root
}
The main functionality:
func convertToList(arr []int) *ListNode {
var head ListNode
for _, val := range arr {
head = *insert(&head, val)
}
return &head
}
A string function implementation to test the function:
func (l *ListNode) String() string {
x := make([]int, 0)
curr := l
for curr != nil {
x = append(x, curr.Val)
curr = curr.Next
}
return fmt.Sprint(x)
}
My main function to replicate output:
func main() {
arr := []int{1, 2, 3, 4, 5}
listNode := convertToList(arr)
fmt.Println(listNode.String())
}
Output:
[1]
Expected Output:
[1 2 3 4 5]
CodePudding user response:
You have to change your convertToList
and insert
functions as:
func insert(root *ListNode, elem int) *ListNode {
temp := ListNode{Val: elem, Next: nil}
if root == nil {
root = &temp
return root
}
curr := root
for curr.Next != nil {
curr = curr.Next
}
curr.Next = &temp
return root
}
and convertToList
:
func convertToList(arr []int) *ListNode {
var head *ListNode
for _, val := range arr {
head = insert(head, val)
}
return head
}
CodePudding user response:
Change convertToList
:
func convertToList(arr []int) *ListNode {
head := new(ListNode)
head.Val = arr[len(arr)-1]
head.Next = nil
// delete first value in list
arr = arr[:len(arr)-1]
for i := len(arr) - 1; i >= 0; i-- {
head = insert(head, arr[i])
}
return head
}
And insert
:
func insert(head *ListNode, val int) *ListNode {
temp := new(ListNode)
temp.Val = val
temp.Next = head
return temp
}
Note : you can't normally shown linked list. If you print list, understood.
// for show linked list:
func Print(head *ListNode) {
fmt.Print("[ ")
for temp := head; temp != nil; temp = temp.Next {
fmt.Print(temp.Val, " ")
}
fmt.Print("]")
}
func main() {
arr := []int{1, 2, 3, 4, 5}
listNode := convertToList(arr)
// You can see different:
fmt.Println("List:", listNode) // List: &{1 0xc00009a080}
Print(listNode) // [ 1 2 3 4 5 ]
}
See this like : linked list for more information