206. 反转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

链接:https://leetcode-cn.com/problems/reverse-linked-list

  1. 迭代
/**
 * 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
    }
        cur := head
        var pre *ListNode = nil
        var tmp *ListNode = nil
        for cur != nil {
/** 
            tmp = cur.Next
            cur.Next = pre
            pre = cur
            cur = tmp
**/
            pre, cur, cur.Next = cur, cur.Next, pre //这句话最重要

        }
        return pre

}
  1. 递归
/**
 * 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
    }
       
    var newHead *ListNode  = reverseList(head.Next);
    head.Next.Next = head
    head.Next = nil
    return newHead
   
}

你可能感兴趣的:(206. 反转链表)