LeetCode-热题100-笔记-day18

234. 回文链表icon-default.png?t=N7T8https://leetcode.cn/problems/palindrome-linked-list/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        Stack stack=new Stack<>();
        ListNode cur=head;
        while(cur!=null){
            stack.push(cur);
            cur=cur.next;
        }
        while(!stack.isEmpty()){
            ListNode tmp=stack.pop();
            if(tmp.val!=head.val){
                return false;
            }
            head=head.next;
        }
        return true;
    }
}

141. 环形链表icon-default.png?t=N7T8https://leetcode.cn/problems/linked-list-cycle/

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        //双指针
        if(head==null||head.next==null){
            return false;
        }
        ListNode fast=head;
        ListNode low=head;
        while(fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            low=low.next;
            if(fast==low){
                return true;
            }
        }
        return false;
    }
}

142. 环形链表 IIicon-default.png?t=N7T8https://leetcode.cn/problems/linked-list-cycle-ii/

 

代码思路

LeetCode-热题100-笔记-day18_第1张图片

快满指针,当fast==slow时,第一次相遇,fast比slow多走了nb步。

如果让指针从链表头部一直向前走并统计步数k,那么所有 走到链表入口节点时的步数 是:k=a+nb,即先走 a步到入口节点,之后每绕 1 圈环( b 步)都会再次到入口节点。而目前 slow 指针走了 nb 步。因此,我们只要想办法让 slow 再走 aaa 步停下来,就可以到环的入口。

作者:Krahets
链接:https://leetcode.cn/problems/linked-list-cycle-ii/solutions/12616/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-/

 

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while (true) {
            if (fast == null || fast.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) break;
        }
        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}

你可能感兴趣的:(leetcode,笔记,算法)