循环链表的反转

206. 反转链表

func reverseList(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }

    p := reverseList(head.Next)

    head.Next.Next = head
    head.Next = nil

    return p
}

循环链表的反转

func reverse(head, key *ListNode) *ListNode {
	if head.Next == key {
		return head
	}
	p := reverse(head.Next, key)
	head.Next.Next = head
	head.Next = p
	return p
}

循环链表的打印

func (l *ListNode) String() string {
	head := l
	var res string
	for {
		res += strconv.Itoa(l.Val)
		res += "->"
		l = l.Next
		if l == head {
			break
		}
	}
	fmt.Println("循环链表循环结束")
	return res
}

你可能感兴趣的:(LeetCode)