|
@@ -0,0 +1,66 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import "fmt"
|
|
|
+
|
|
|
+func main() {
|
|
|
+ var vals []int
|
|
|
+
|
|
|
+ vals = []int{}
|
|
|
+ printList(reverseList(createList(vals)))
|
|
|
+
|
|
|
+ vals = []int{1}
|
|
|
+ printList(reverseList(createList(vals)))
|
|
|
+
|
|
|
+ vals = []int{1, 2}
|
|
|
+ printList(reverseList(createList(vals)))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ printList(reverseList(createList(vals)))
|
|
|
+}
|
|
|
+
|
|
|
+func createList(vals []int) *ListNode {
|
|
|
+ var head, list *ListNode
|
|
|
+ for _, v := range vals {
|
|
|
+ if head == nil {
|
|
|
+ list = &ListNode{Val: v, Next: nil}
|
|
|
+ head = list
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ var temp = &ListNode{Val: v, Next: nil}
|
|
|
+ list.Next = temp
|
|
|
+ list = list.Next
|
|
|
+ }
|
|
|
+ return head
|
|
|
+}
|
|
|
+
|
|
|
+func printList(node *ListNode) {
|
|
|
+ var temp = node
|
|
|
+ for temp != nil {
|
|
|
+ fmt.Printf("%d", temp.Val)
|
|
|
+ if temp.Next != nil {
|
|
|
+ fmt.Printf("%s", "->")
|
|
|
+ }
|
|
|
+ temp = temp.Next
|
|
|
+ }
|
|
|
+ fmt.Println()
|
|
|
+}
|
|
|
+
|
|
|
+//Definition for singly-linked list.
|
|
|
+type ListNode struct {
|
|
|
+ Val int
|
|
|
+ Next *ListNode
|
|
|
+}
|
|
|
+
|
|
|
+func reverseList(head *ListNode) *ListNode {
|
|
|
+ var cursor = head
|
|
|
+ var ans = &ListNode{}
|
|
|
+ for cursor != nil {
|
|
|
+ var temp = &ListNode{
|
|
|
+ Val: cursor.Val,
|
|
|
+ Next: ans.Next,
|
|
|
+ }
|
|
|
+ ans.Next = temp
|
|
|
+ cursor = cursor.Next
|
|
|
+ }
|
|
|
+ return ans.Next
|
|
|
+}
|