反转链表go语言手撕(Goland上编写)

在Goland上手写反转链表,并且写出例子运行一下。好久没写力扣,有点手生了,面试官说,如果我好久没写这个,就最好不要在简历上写,他说他是希望我能够手撕算法的。

算是积累经验了。。

package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func reverseList(head *ListNode) *ListNode {
	var before *ListNode
	var now *ListNode
	now = head
	for now != nil {
		next := now.Next
		now.Next = before
		before = now
		now = next
	}
	return before
}

func printList(head *ListNode) {
	cur := head
	for cur != nil {
		fmt.Printf("%d ", cur.Val)
		cur = cur.Next
	}
	fmt.Println("")
}

func main() {
	a := &ListNode{Val: 1}
	b := &ListNode{Val: 2}
	c := &ListNode{Val: 3}
	d := &ListNode{Val: 4}
	e := &ListNode{Val: 5}
	a.Next = b
	b.Next = c
	c.Next = d
	d.Next = e
	e.Next = nil
	printList(a)

	x := reverseList(a)
	printList(x)

}

猜你喜欢

转载自blog.csdn.net/e2788666/article/details/131785364