给定单个链表,使用java在单个链表中查找中点或中间节点,使用非递归或迭代算法遍历单个链表

5 篇文章 0 订阅

又get到了一个技能!继续刷题锻炼思维能力

上题

题目:Middle of the Linked List
题干:
Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.

Example 2:

Input: [1,2,3,4,5,6] 
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
 ```
Note:

The number of nodes in the given list will be between 1 and 100.

```java
这是那个链表
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

大意就是我给你一组数据,然后你从中给我得出中间的那个数字,奇数个返回n+1/2那个数(其实是列表ListNode ),偶数返回n/2那个数(其实是列表ListNode )。

这里用到了快慢指针
画了个图这里写图片描述
先放程序吧

  public ListNode middleNode(ListNode head) {
    ListNode fast = head;
    ListNode slow = head;
    //这里是因为head的长度可能是奇数或者偶数,所以用了
    //fast != null || fast.next != null
    while(fast != null || fast.next != null){
        fast = fast.next.next;
        slow = slow.next;
    }
    return slow;      
  }

就像这个链表,7个数字,依照题意是返回第四个数字4,slow会依次遍历1/2/3/4/5/6/7,fast会依次遍历1/3/5/7,也就是说快指针fast每次走的步数是慢指针slow的两倍,所以当fast遍历到最后一位了,或者即将遍历到最后以为了,slow走到了中间。然后返回slow即可。

emmm,算法方面确实是目前程序员所或缺的,也不是说要求你都会什么什么算法,对某个算法研究多精深,说实话,你不是个研究生或者博士,你还真不行,现阶段,普通本科出身去练习算法,一个是练习逻辑思维能力,另外一个是了解算法,找出最优解,见多,识广。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值