Reverse a linked list using golang Online study

In this post we are going to implement a golang program which reverse a linked list without recursion.

reverselinkedlist

 

In this algorithm, Our target is too not use any recursive method here, we are going to use a temporary node pointer  which help us to break and make linking between nodes.

Note: we are not going to just print the linked list, here our main focus is to make the entire link list reverse. In interview this is most frequent question asked in many data structure coding interview that how we going to reverse a linked list not only to print the list but our target is to change the pointer link form selected node and join it to previous one.

Go code for linkedlist:

 

package main

import (
	"fmt"
)

//Create prototype

//LL container which going to store list
type LL struct {
	list *linklist
}

//linklist for value and next pointer details
type linklist struct {
	val  int
	next *linklist
}

// createNode use for create node for list
func createNode(value int) *linklist {
	return &linklist{
		val:  value,
		next: nil,
	}
}

func (lstVal *LL) insertAtBeginning(data int) {
	if nil == lstVal.list {
		lstVal.list = createNode(data)
		return
	}

	tempNode := createNode(data)
	head := lstVal.list
	tempNode.next = head
	lstVal.list = tempNode
}

func (lstVal *LL) printList() {
	if nil != lstVal && nil != lstVal.list {
		head := lstVal.list
		for nil != head {
			fmt.Printf(" %d", head.val)
			head = head.next
		}
	}
	fmt.Println()
}

func reverseLinkedList(ll *linklist) *linklist {
	var tempNode *linklist
	for ll != nil {
		next := ll.next
		ll.next = tempNode
		tempNode = ll
		ll = next
	}
	return tempNode
}



func main() {
	staticList := []int{5, 7, 1, 3, 4, 9}
	linklst := new(LL)
	//linklst.list = new(linklist)
	//var firstTime bool = true
	for _, value := range staticList {
		linklst.insertAtBeginning(value)
	}
	fmt.Println("PrintList")
	linklst.printList()
	linklst.list = reverseLinkedList(linklst.list)
	fmt.Println("After reverse")
	linklst.printList()
}


 

 

Please check the code and let me know if any change required, we also post other important linked list and binary tree question which mostly asked in interview.Check as well which might be helpful to you in your preparation, if you need any help regarding your preparation let me know in comment.

Post a Comment

0 Comments