Leetcode - Remove Zero Sum Consecutive Nodes from Linked List
Leetcode - Reverse Linked List II

Leetcode - Reverse Linked List

violet posted @ Jun 05, 2020 08:40:24 AM in 算法 with tags Algorithm Linked List Golang , 271 阅读

https://leetcode.com/problems/reverse-linked-list/

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    node := head
    for node != nil {
        tmp := node.Next
        node.Next = prev
        prev = node
        node = tmp
    }
    return prev
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter