Browse Source

add 反转链表

tangs 2 years ago
parent
commit
7827203e80
1 changed files with 60 additions and 0 deletions
  1. 60 0
      leetcode/剑指offer/反转链表/main.go

+ 60 - 0
leetcode/剑指offer/反转链表/main.go

@@ -0,0 +1,60 @@
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"os"
+	"strconv"
+	"strings"
+)
+
+func main() {
+	input := bufio.NewScanner(os.Stdin)
+	for input.Scan() {
+		line := input.Text()
+		var values = strings.Split(line, " ")
+		var digits []int
+		var num int
+		for _, v := range values {
+			num, _ = strconv.Atoi(v)
+			digits = append(digits, num)
+		}
+
+		var head *ListNode
+		var cur *ListNode = head
+		for _, v := range digits {
+			var tmp = &ListNode{Val: v, Next: nil}
+			if head == nil {
+				head = tmp
+				cur = head
+				continue
+			}
+			cur.Next = tmp
+			cur = tmp
+		}
+		newHead := reverseList(head)
+		for newHead != nil {
+			fmt.Println(newHead.Val)
+			newHead = newHead.Next
+		}
+	}
+}
+
+type ListNode struct {
+	Val  int
+	Next *ListNode
+}
+
+func reverseList(head *ListNode) *ListNode {
+	var newHead *ListNode
+	for head != nil {
+		var tmpNode = &ListNode{
+			Val:  head.Val,
+			Next: newHead,
+		}
+		newHead = tmpNode
+		head = head.Next
+	}
+
+	return newHead
+}