day007

 环形链表

141. 环形链表

给你一个链表的头节点 head ,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。

如果链表中存在环 ,则返回 true 。 否则,返回 false 。

想到的有两种解法:

1、通过快慢指针,循环链表,如果两个指针相遇了,那表示链表是有环的

2、哈希表,如果添加有重复数据,add方法就会返回false,然后可以判断是有环的了

/**
 * 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) {
        //快慢指针做题
        // ListNode p,q;
        // p=q=head;
        // while(q!=null && q.next!=null&&p!=null &&p.next!=null){
        //     p=p.next;//慢指针
        //     q=q.next.next;//快指针

        //     if(q==p)
        //         return true;
        // }
        // return false;

        //哈希表找重复
         Set seen = new HashSet();
        while(head != null && head.next != null){
            if(!seen.add(head) ){
                return true;
            }
            head = head.next;
        }
        return false;
    }
}

 

旋转链表

61. 旋转链表

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置

/**
 * 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 ListNode rotateRight(ListNode head, int k) {
        //无脑暴力破解
        // if(k == 0 || head == null || head.next == null)
        //     return head;
        // ListNode p=head;
        // int count=0;
        // while(p != null){
        //     count++;
        //     p=p.next;
        // }
        
        // if(k t){
        //         count += t;
        //     }
        //     k = count - k;
        // }
        // if(k == count || k == 0)
        //     return head;
        // p=head;
        // ListNode q=p.next;
        // while(--k > 0){
        //         p=q;
        //         q=q.next;
        // }
        // p.next =null;
        // p=q;
        // while(q.next != null)
        //     q=q.next;

        // q.next = head;

        // return p;

        //官方答案,发现整体思路差不多
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        int add = n - k % n;//官方的精髓
        if (add == n) {
            return head;
        }
        iter.next = head;
        while (add-- > 0) {
            iter = iter.next;
        }
        ListNode ret = iter.next;
        iter.next = null;
        return ret;
    }
    
}

 

你可能感兴趣的:(算法)