首页 > 其他分享 >206. 反转链表

206. 反转链表

时间:2024-06-07 15:12:11浏览次数:29  
标签:head ListNode cur 206 反转 list Next 链表

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

标签:head,ListNode,cur,206,反转,list,Next,链表
From: https://www.cnblogs.com/gdut17code/p/18237237

相关文章