Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign up关于中点问题 #25
关于中点问题 #25
Comments
|
实现了一下: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就没法找到了 |

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.

https://github.com/greyireland/algorithm-pattern/blob/master/data_structure/linked_list.md
里面说"fast 如果初始化为 head.Next 则中点在 slow.Next
如果链表长度是偶数,返回中间偏右的位置
且fast如果初始化为head->next 返回中间偏左的位置。
但是对于奇数长度两者中点相同吧