206. 反转链表

package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func reverseList(head *ListNode) *ListNode {
	var pre *ListNode // 前驱节点指针
	cur := head       // 当前节点指针
	for cur != nil {
		next := cur.Next // 临时存储next指针
		cur.Next = pre   // next指针反转

		pre = cur
		cur = next
	}
	return pre
}

func main() {
	list := createList(5)
	printList(list)
	list = reverseList(list)
	printList(list)
}

// 创建链表
func createList(sz int) *ListNode {
	head := &ListNode{}
	tail := head
	for i := 0; i < 5; i++ {
		node := &ListNode{Val: i}
		tail.Next = node
		tail = node
	}
	return head.Next
}

// 打印链表
func printList(head *ListNode) {
	for p := head.Next; p != nil; p = p.Next {
		fmt.Printf("%d ", p.Val)
	}
	fmt.Println()
}

PS C:\Users\wushujie\Desktop\leetcode\code> go run .\reverse-linked-list.go
1 2 3 4
3 2 1 0

posted @ 2024-06-07 15:06  gdut17_2  阅读(16)  评论(0)    收藏  举报