Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

golang 19题链表反转 超时 #68

Open
IT-Talon opened this issue Aug 23, 2023 · 0 comments
Open

golang 19题链表反转 超时 #68

IT-Talon opened this issue Aug 23, 2023 · 0 comments

Comments

@IT-Talon
Copy link
Contributor

代码如下

package main

import "fmt"

func main() {
	for {
		var n int
		_, err := fmt.Scan(&n)
		if err != nil {
			return
		}
		if n == 0 {
			fmt.Println("list is empty")
			continue
		}
		var head *Node
		dummyNode := &Node{next: head}
		temp := dummyNode
		for n > 0 {
			var num int
			_, err = fmt.Scan(&num)
			if err != nil {
				return
			}
			newNode := &Node{val: num}
			temp.next = newNode
			temp = temp.next
			n--
		}
		head = dummyNode.next
		show(head)
		show(head.reverse())
	}
}

func show(head *Node) {
	if head == nil {
		return
	}
	cur := head
	for cur != nil {
		fmt.Printf("%d ", cur.val)
		cur = cur.next
	}
	fmt.Println()
}

type Node struct {
	val  int
	next *Node
}

func (l *Node) reverse() *Node {
	if l == nil || l.next == nil {
		return l
	}
	var pre *Node
	cur := l
	for cur != nil {
		temp := cur.next
		cur.next = pre
		pre = cur
		cur = temp
	}
	return pre
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant