《剑指Offer》24-反转链表

反转链表的几种方法

1-最基础

image-20220129151235626

func reverseList_1(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}
	if head.Next == nil {
		return head
	}
	p := head
	q := p.Next
	s := q.Next
	for s != nil {
		q.Next = p
		p = q
		q = s
		s = s.Next
	}
	q.Next = p
	head.Next = nil
	head = q
	return head
}

2-迭代

image-20220129151758237

// 法2:迭代;
func reverseList_2(head *ListNode) *ListNode {
	var prev *ListNode
	cur := head
	for cur != nil {
		next := cur.Next
		cur.Next = prev
		prev = cur
		cur = next
	}
	return prev
}

3-递归

image-20220129151729300

// 法3:递归;
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
}

posted @ 2022-01-29 15:20  KpHang  阅读(11)  评论(0编辑  收藏  举报