Difference between the 2 insertion functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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