| by suyi | No comments

Go:反转链表

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    node := &ListNode{0,nil}
    for head != nil {
        node.Next, head, head.Next = head, head.Next, node.Next
    }

    return node.Next
}
/**
 * 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
    }

    // 递归
    node := reverseList(head.Next)
    head.Next.Next = head
    head.Next = nil
    return node
}

发表评论