LeetCode 141判断链表是否有环[附创建链表的代码]

LeetCode上面的141题,同时也是昨晚携程笔试编程的第1题。当时那个函数很快就写出来了,但是在创建环形链表这儿一直绕不出来,花了很长时间。下来跟大家讨论才知道有的人有HashMap解决了,HashSet也有的解决了,还有的直接用一个char数组给解决了。

还是把自己的方法整理一下

思路就是两个指针,一个每次向前跑两个,一个向前跑一个,如果在某一个时间点,两者重复了,就说明是环形链表

函数如下:
 

public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode p = head.next, q = head;
        while (p != q) {
            if (p == null || p.next == null)
                return false;
            else {
                p = p.next.next;
                q = q.next;
            }
        }
        return true;
    }

完整的代码如下:
创建链表的思路;如果有某一个新的节点的值等于之前的结点值,把这个链表的next指向找到的那个节点

public class Num141 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        String[] ss = s.split(",");
        ListNode head = new ListNode(ss);
        System.out.println(hasCycle(head));
    }

    public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode p = head.next, q = head;
        while (p != q) {
            if (p == null || p.next == null)
                return false;
            else {
                p = p.next.next;
                q = q.next;
            }
        }
        return true;
    }


    static class ListNode {
        String value;
        ListNode next;

        ListNode(String value) {
            this.value = value;
        }

        public ListNode(String[] arr) {
            ListNode p;
            if (arr == null || arr.length <= 0) {
                throw new IllegalArgumentException("参数错误");
            }
            this.value = arr[0];
            ListNode cur = this;
            for (int i = 1; i < arr.length; i++) {
                ListNode temp = new ListNode(arr[i]);
                temp.next = null;
                for (p = this; p != null; p = p.next) {
                    if (p.value.equals(temp.value)) {
                        cur.next = temp;
                        temp.next = p;
                        return;
                    }
                }
                cur.next = temp;
                cur = cur.next;
            }
        }
    }
}

 

你可能感兴趣的:(算法-基础算法,算法-LeetCode,算法-剑指offer)