Created
September 11, 2019 10:07
-
-
Save islishude/14678b9511f1e93f3a6c39a2d5ba223e to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
func main() { | |
list := []int{1, 2, 3, 4} | |
{ | |
head := createLinkedListBySlice(list) | |
for { | |
fmt.Println(head.Value) | |
head = head.Next | |
if head == nil { | |
break | |
} | |
} | |
} | |
fmt.Println("===") | |
{ | |
head := reverseLinkedList(createLinkedListBySlice(list)) | |
for { | |
fmt.Println(head.Value) | |
head = head.Next | |
if head == nil { | |
break | |
} | |
} | |
} | |
} | |
type LinkedList struct { | |
Value int | |
Next *LinkedList | |
} | |
func NewLinedList(value int) *LinkedList { | |
return &LinkedList{ | |
Value: value, | |
} | |
} | |
func (l *LinkedList) SetNext(next *LinkedList) { | |
l.Next = next | |
} | |
func createLinkedListBySlice(list []int) *LinkedList { | |
if len(list) == 0 { | |
return nil | |
} | |
// get first value | |
head := NewLinedList(list[0]) | |
var subSlice []int | |
if len(list) > 1 { | |
subSlice = list[1:len(list)] | |
} | |
head.SetNext(createLinkedListBySlice(subSlice)) | |
return head | |
} | |
func reverseLinkedList(head *LinkedList) *LinkedList { | |
if head == nil || head.Next == nil { | |
return head | |
} | |
newHead := reverseLinkedList(head.Next) | |
head.Next.SetNext(head) | |
head.Next = nil | |
return newHead | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment