DEV Community

vinay
vinay

Posted on

Linked list golang and python

class Node:
    def __init__(self,value):
        self.value = value
        self.adress=None
# creating a head and tail
class linkedList:
    def __init__(self):
        self.head=None
        self.tail=None
        self.size=0


    def addvalue(self,v):
        newest=Node(v)
        if self.size==0:
            self.head=newest
        else:
            self.tail.adress=newest
        self.tail=newest
        self.size+=1
    def addfirst(self, e):
        newest = Node(e)
        if self.size==0:
            self.head = newest
            self.tail = newest
        else:
            newest.adress= self.head
            self.head = newest
    def addany(self, e, position):
        newest = Node(e)
        p = self.head
        i = 1
        while i < position-1:
            p = p.adress
            i = i + 1
        newest.adress = p.adress
        p.adress = newest
        self.size += 1


    def display(self):
        print("head val:",self.head.value)
        p=self.head
        while p:
            print(p.value,end=" ")
            p=p.adress
        print()
        print("tail val: ",self.tail.value)


l=linkedList()
l.addvalue(10)
l.addvalue(20)
l.addvalue(30)
l.addvalue(40)
l.addvalue(50)
l.addvalue(60)
l.addany(70,3)
l.addfirst(80)
l.addfirst(90)
l.display()
Enter fullscreen mode Exit fullscreen mode
package main

import (
    "fmt"
)

type Node struct {
    value  interface{}
    adress *Node
}

type List struct {
    head *Node
    tail *Node
    size int
}

func (l *List) Insert(d interface{}) {
    list := &Node{value: d, adress: nil}
    if l.size == 0 {
        l.head = list
    } else {
        l.tail.adress = list
    }
    l.tail = list
    l.size++
}

func (l *List) addfirst(d interface{}) {
    list := &Node{value: d, adress: nil}
    if l.size == 0 {
        l.head = list
        l.tail = list
    } else {
        list.adress = l.head
        l.head = list
    }
}

func (l *List) addany(d interface{}, position int) {
    list := &Node{value: d, adress: nil}
    p := l.head
    i := 1
    for i < position-1 {
        p = p.adress
        i = i + 1
    }
    list.adress = p.adress
    p.adress = list
    l.size += 1

}

func (l *List) display() {
    p := l.head
    fmt.Println(l.head.value)
    for p != nil {
        fmt.Print(p.value, " ")
        p = p.adress
    }
    fmt.Println()
    fmt.Print(l.tail.value)
    fmt.Println("")
    fmt.Print(l.size)
}

func main() {
    link := List{}
    link.Insert(5)
    link.Insert(9)
    link.Insert(13)
    link.Insert(22)
    link.Insert(28)
    link.Insert(36)
    link.addany(70, 3)
    link.addfirst(80)
    link.display()
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)