Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于中点问题 #25

Open
voidbytes opened this issue Jul 24, 2020 · 1 comment
Open

关于中点问题 #25

voidbytes opened this issue Jul 24, 2020 · 1 comment

Comments

@voidbytes
Copy link

https://github.com/greyireland/algorithm-pattern/blob/master/data_structure/linked_list.md
里面说"fast 如果初始化为 head.Next 则中点在 slow.Next

如果链表长度是偶数,返回中间偏右的位置
且fast如果初始化为head->next 返回中间偏左的位置。

但是对于奇数长度两者中点相同吧

  1. 链表的中间结点:https://leetcode-cn.com/problems/middle-of-the-linked-list/
@greyireland
Copy link
Owner

实现了一下:https://leetcode-cn.com/problems/middle-of-the-linked-list/

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func middleNode(head *ListNode) *ListNode {
    // v1
    // 1->2->3->4->5->nil
    // 1->2->3->4->5->6->nil
    if head==nil{
        return nil
    }
    fast := head
    slow := head
    for fast != nil && fast.Next != nil {
        fast = fast.Next.Next
        slow = slow.Next
    }
    return slow
}
func middleNode2(head *ListNode) *ListNode {
    // v2分为两种情况:
    // 1->2->3->4->5->nil
    // 1->2->3->4->5->6->nil
    if head==nil{
        return nil
    }
    fast := head.Next
    slow := head
    for fast != nil && fast.Next != nil {
        fast = fast.Next.Next
        slow = slow.Next
    }
    if fast==nil{
        return slow
    }
    return slow.Next
}

这个题只是要求找中点,所以v1可能更简单一点,但如果要从中间分开这个链表,需要找到链表中点的前一个节点,v1就没法找到了
可以试试这两个题:

https://leetcode-cn.com/problems/sort-list/

https://leetcode-cn.com/problems/reorder-list/

gitbook-com bot pushed a commit to zhangzz2015/algorithm-pattern that referenced this issue Jan 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants