Golang Program to update the node value after the Kth node.

Go ProgrammingServer Side ProgrammingProgramming

<h2>Examples</h2><p><img src="https://www.tutorialspoint.com/assets/questions/media/49973/linked1.jpg" class="fr-fic fr-dib" width="600" height="88"></p><p>Update node after k=10 value node</p><p><strong>Approach to solve this problem</strong></p><p><strong>Step 1</strong> &minus; Define a method that accepts the head of a linked list.</p><p><strong>Step 2</strong> &minus; If head == nil, return the head.</p><p><strong>Step 3</strong> &minus; Iterate the given linked list.</p><p><strong>Step 4</strong> &minus; If <strong>temp.value</strong> is 10, then update <strong>temp.next.value=data.</strong></p><p><strong>Step 5</strong> &minus; If node value 10 is not found, return the head without updating any node.</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/HdF1BLt4" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranalate" style="">package main import &quot;fmt&quot; type Node struct { &nbsp; &nbsp;value int &nbsp; &nbsp;next *Node } func NewNode(value int, next *Node) *Node{ &nbsp; &nbsp;var n Node &nbsp; &nbsp;n.value = value &nbsp; &nbsp;n.next = next &nbsp; &nbsp;return &amp;n } func TraverseLinkedList(head *Node){ &nbsp; &nbsp;temp := head &nbsp; &nbsp;for temp != nil { &nbsp; &nbsp; &nbsp; fmt.Printf(&quot;%d &quot;, temp.value) &nbsp; &nbsp; &nbsp; temp = temp.next &nbsp; &nbsp;} &nbsp; &nbsp;fmt.Println() } func UpdateAfterKthNode(head *Node, k, data int) *Node{ &nbsp; &nbsp;// Update after Kth node. &nbsp; &nbsp;if head == nil{ &nbsp; &nbsp; &nbsp; return head &nbsp; &nbsp;} &nbsp; &nbsp;temp := head &nbsp; &nbsp;for temp != nil{ &nbsp; &nbsp; &nbsp; if temp.value == k{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;temp.next.value = data &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; temp = temp.next &nbsp; &nbsp;} &nbsp; &nbsp;return head } func main(){ &nbsp; &nbsp;head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil)))) &nbsp; &nbsp;fmt.Printf(&quot;Input Linked list is: &quot;) &nbsp; &nbsp;TraverseLinkedList(head) &nbsp; &nbsp;head = UpdateAfterKthNode(head, 10, 15) &nbsp; &nbsp;fmt.Printf(&quot;Update node after %dth value node, Linked List is: &quot;, 10) &nbsp; &nbsp;TraverseLinkedList(head) }</pre><h2>Output</h2><pre class="result notranalate">Input Linked list is: 30 10 40 40 Update node after 10th value node, Linked List is: 30 10 15 40</pre>
Updated on 18-Mar-2021 06:32:36