-
-
Save AahanSingh/6e6ccf4e84a93a6838f3c88e77de4791 to your computer and use it in GitHub Desktop.
CList insert at p
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
func InsertAtP(head **Node, p int, x int) { | |
if p < 1 { | |
fmt.Println("\nPositions start at 1. Invalid input position.") | |
return | |
} | |
if p == 1 { | |
InsertAtStart(head, x) | |
return | |
} | |
// If insertion point is not the start and the list is empty, insertion point is invalid. | |
if *head == nil { | |
fmt.Println("\nInvalid Position.") | |
return | |
} | |
current := *head | |
i := 1 | |
for i < p-1 && current.Next != *head { | |
current = current.Next | |
i++ | |
} | |
if i < p-1 { | |
fmt.Println("\nInvalid Position") | |
return | |
} | |
tmp := &Node{Data: x} | |
tmp.Next = tmp | |
fmt.Println("\nInserting", tmp, "at the position", p) | |
tmp.Next = current.Next | |
current.Next = tmp | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment