• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

Recommended Posts

标题:876。链表的中间节点-LEET代码(leetcode-cn.com)

想法:

这个问题可以用快慢指针的方法,根据慢指针走一步,快指针走两步的情况。

A.如果链表中的节点数为奇数,则有一个中间节点:

可以推导出当快速指针fast到达链表的最后一个节点时(fast!=null和fast.next==null),慢速指针指向中间节点;

B.如果链表中的节点数是偶数,则有两个中间节点:

可以推断,当快指针fast到达最后一个节点(fast==null且fast.next==null)时,慢指针指向第二个中间节点;

代码:

/**

*单链表的定义。

*公共类ListNode {

* int val

* ListNode next

* ListNode() {}

* list node(int val){ this . val=val;}

* ListNode(int val,ListNode next){ this . val=val;this.next=next}

* }

*/

类别解决方案{

公共ListNode middle node(ListNode head){

ListNode慢,快;

慢=快=头;

而(快!=null fast .下一个!=null){

fast=fast . next . next;

slow=slow.next

}

返回慢;

}

}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now