---
# System prepended metadata

title: 反转一个单链表
tags: [LeeCode]

---

# 反转一个单链表
---

```javascript=
示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
```

:::success
```go=
package main

import "fmt"

func printNode(head *ListNode) {
	for head != nil {
		fmt.Println(head)
		head = head.Next
	}
	fmt.Println()
}

func main() {
	a := []int{1, 2, 3, 4}
	node4 := &ListNode {a[3], nil}
	node3 := &ListNode {a[2], node4}
	node2 := &ListNode {a[1], node3}
	node1 := &ListNode {a[0], node2}
	printNode(node1)
	printNode(reverseList(node1))
}

type ListNode struct {
	Value int
	Next  *ListNode
}

func reverseList(head *ListNode) *ListNode {
	// prev 前一个节点
	// next 后一个节点
	var prev, next *ListNode

	for head != nil {
		//  保存头节点的下一个节点
		next = head.Next
		//  将头节点指向前一个节点
		head.Next = prev
		//  更新前一个节点
		prev = head
		//  更新头节点
		head = next
	}

	return prev
}

- 结果输出

&{1 0xc0000421f0}
&{2 0xc0000421e0}
&{3 0xc0000421d0}
&{4 <nil>}

&{4 0xc0000421e0}
&{3 0xc0000421f0}
&{2 0xc000042200}
&{1 <nil>}
```
:::

:::success
```go=
// Definition for singly-linked list.
type ListNode struct {
    Value int
    Next *ListNode
}
 
func reverseList(head *ListNode) *ListNode {
	var cur *ListNode

	for head != nil {
		cur, head, head.Next = head, head.Next, cur
	}

	return cur
}
```
:::

###### tags: `LeeCode`