Skip to content

Instantly share code, notes, and snippets.

@AahanSingh
Last active June 27, 2021 06:51
Show Gist options
  • Save AahanSingh/3c09f02894e04ffc37237786ae86de43 to your computer and use it in GitHub Desktop.
Save AahanSingh/3c09f02894e04ffc37237786ae86de43 to your computer and use it in GitHub Desktop.
Difference between the 2 insertion functions
package main
import (
"fmt"
)
type Node struct {
Data int
Next *Node
}
func DisplayList(head *Node) {
fmt.Printf("The list is: ")
for ; head != nil; head = head.Next {
fmt.Print(head.Data, " ")
}
fmt.Println()
}
// This modifies the head pointer in the calling function
func InsertAtEndInPlace(head **Node, x int) {
fmt.Println("\nIn InsertAtEndInPlace:")
tmp := Node{Next: nil, Data: x}
fmt.Println("Inserting", tmp, "at the end")
if *head == nil {
*head = &tmp
} else {
var p *Node
p = *head
for ; p.Next != nil; p = p.Next {
}
p.Next = &tmp
}
fmt.Printf("Address of head node %p\n", &**head)
fmt.Println("Address of head pointer ", &*head)
fmt.Println("Returning")
}
// This returns the head
func InsertAtEnd(head *Node, x int) *Node {
fmt.Println("\nIn InsertAtEnd:")
tmp := Node{Next: nil, Data: x}
fmt.Println("Inserting", tmp, "at the end")
current := head
if head == nil {
head = &tmp
} else {
for ; current.Next != nil; current = current.Next {
}
current.Next = &tmp
}
fmt.Printf("Address of node %p\n", &*head)
fmt.Println("Address of head pointer ", &head)
fmt.Println("Returning")
return head
}
func main() {
var p *Node
p = nil
// Linked List Insertion
InsertAtEndInPlace(&p, 2020)
fmt.Printf("Adderss of node p %p\n", &*p)
fmt.Println("Address of pointer p ", &p)
DisplayList(p)
p = InsertAtEnd(p, 1234)
fmt.Printf("Adderss of node p %p\n", &*p)
fmt.Println("Address of pointer p ", &p)
DisplayList(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment