浏览代码

add 'Reverse Linked List'

tangs 5 年之前
父节点
当前提交
d94acaccde
共有 1 个文件被更改,包括 66 次插入0 次删除
  1. 66 0
      tags/linked-list/reverseLinkedList/main.go

+ 66 - 0
tags/linked-list/reverseLinkedList/main.go

@@ -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
+}