秋招链表总结

1.双指针法

链表这里的题感觉大多双指针都能解决,比如环形链表、环形链表Ⅱ(重点背一下方法)、相交链表、倒数第n个几点、链表中间节点等,这里的都是利用快慢指针的思想来解决的。

之后就是合并两个有序链表、和分割链表,这两个是属于合并和拆分链表,最好单独弄一个链表头,这样思路会清洗很多

逆置链表也可以用双指针法,不过也可以用递归方法

2.递归法逆置链表

逆置整个链表:

func reverseList(head *ListNode) *ListNode {

    if head == nil || head.Next == nil {
        return head
    }

    last := reverseList(head.Next)
    head.Next.Next = head
    head.Next = nil
    return last
}

逆置前n个链表

var successer *ListNode

func reverseBetween(head *ListNode, left int, right int) *ListNode {

    if left == 1 {
        return reverseN(head,right)
    }
    left--
    right--
   head.Next = reverseBetween(head.Next,left,right)

   return head
}

func reverseN(head *ListNode,n int) *ListNode {

    if n == 1 {
        successer = head.Next
        return head
    }
    n--
    last := reverseN(head.Next,n)

    head.Next.Next = head
    head.Next = successer
    return last

}

k个一组逆置链表:

func reverseKGroup(head *ListNode, k int) *ListNode {

    n := k
    ptr := head
    for k > 0 {
        if ptr == nil {
            return head
        }
        k--
        ptr = ptr.Next
    }

    

    newHeae := reverseAtoB(head,ptr)
    head.Next = reverseKGroup(ptr,n)

    return newHeae

}
//左闭右开
func reverseAtoB(a,b *ListNode) *ListNode {
    
    var pre *ListNode
    cur,next := a,a

    for cur != b {
        next = cur.Next
        cur.Next = pre
        pre = cur
        cur = next
    }
    return pre
}

3.非递归法逆置整个链表

//左闭右开
func reverseAtoB(a,b *ListNode) *ListNode {
    
    var pre *ListNode
    cur,next := a,a

    for cur != b {
        next = cur.Next
        cur.Next = pre
        pre = cur
        cur = next
    }
    return pre
}

你可能感兴趣的:(leetcode刷题总结,链表,数据结构)