难度:简单 题目来源:力扣(LeetCode) https://leetcode-cn.com/problems/reverse-linked-list
说明:
反转一个单链表。
示例:_
输入:1->2->3->4->5->NULL 输出:5->4->3->2->1->NULL
解法:
常规遍历
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
var tmp *ListNode
for head != nil {
tmp = &ListNode{Val: head.Val, Next: tmp}
head = head.Next
}
return tmp
}
递归**
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
last := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return last
}