链表判环问题

给定一单链表的头指针head

1、判断链表是否又环。

2、如果有环,求环长以及环的起始节点。

package aglist;

class Node{
    public final int value;
    public Node next = null;
    Node(int value){
        this.value = value;
    }
    public static void addTail(Node head,Node node){
        Node temp = head;
        while(temp.next != null){
            temp = temp.next;
        }
        temp.next = node;
    }
    public static Node getNode(Node head,int index){
        int i = 0;
        Node temp = head;
        while(i < index && temp.next != null){
            temp = temp.next;
            i++;
        }
        return temp;
    }
    public static Node getTail(Node head){
        Node temp = head;
        while(temp.next != null){
            temp = temp.next;
        }
        return temp;
    }
}
public class Circle {
    public static boolean hasCircle(Node head){
        Node fast = head,slow = head;//两指针,一个步长为1,一个步长为2
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow){return true;}//两指针相遇,必有环,且相遇点在环内
        }
        return false;
    }
    private static Node getMeetNode(Node head){
        Node fast = head,slow = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow){break;}
        }
        return fast;
    }
    private static int getLengthOfCircle(Node meetNode){
        int length = 1;
        Node temp = meetNode.next;
        while(temp != meetNode){//由于相遇点必在环内,只要顺着环走一圈,即可获得环的长度
            length++;
            temp = temp.next;
        }
        return length;
    }
    /*
     * 在相遇点将环分开,视为形成两个单链表
     * 一个单链表以head为头
     * 另一个单链表以meetNode为头
     * 该问题进而规约为求两个单链表的交点,交点即为环的起点
     * 并且其交点到两链表头等长
     * */
    private static Node getStartOfCircle(Node head,Node meetNode){
        while(head != meetNode){
            head = head.next;
            meetNode = meetNode.next;
        }
        return meetNode;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            int[] ary = {3,4,5,7,1,40,10,50};
            Node head = new Node(30);
            for (int i = 0; i < ary.length; i++) {
                Node.addTail(head, new Node(ary[i]));
            }
            Node.getTail(head).next = Node.getNode(head, 0);
            if (hasCircle(head)) {
                Node meetNode = getMeetNode(head);
                int lenght = getLengthOfCircle(meetNode);
                Node start = getStartOfCircle(head, meetNode);
                System.out.println("length:"+lenght);
                System.out.println("StartNode:"+start.value);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

package aglist;
class Node{public final int value;public Node next = null;Node(int value){this.value = value;}public static void addTail(Node head,Node node){Node temp = head;while(temp.next != null){temp = temp.next;}temp.next = node;}public static Node getNode(Node head,int index){int i = 0;Node temp = head;while(i < index && temp.next != null){temp = temp.next;i++;}return temp;}public static Node getTail(Node head){Node temp = head;while(temp.next != null){temp = temp.next;}return temp;}}public class Circle {public static boolean hasCircle(Node head){Node fast = head,slow = head;//两指针,一个步长为1,一个步长为2while(fast.next != null && fast.next.next != null){slow = slow.next;fast = fast.next.next;if(fast == slow){return true;}//两指针相遇,必有环,且相遇点在环内}return false;}private static Node getMeetNode(Node head){Node fast = head,slow = head;while(fast.next != null && fast.next.next != null){slow = slow.next;fast = fast.next.next;if(fast == slow){break;}}return fast;}private static int getLengthOfCircle(Node meetNode){int length = 1;Node temp = meetNode.next;while(temp != meetNode){//由于相遇点必在环内,只要顺着环走一圈,即可获得环的长度length++;temp = temp.next;}return length;}/* * 在相遇点将环分开,视为形成两个单链表 * 一个单链表以head为头 * 另一个单链表以meetNode为头 * 该问题进而规约为求两个单链表的交点,交点即为环的起点 * 并且其交点到两链表头等长 * */private static Node getStartOfCircle(Node head,Node meetNode){while(head != meetNode){head = head.next;meetNode = meetNode.next;}return meetNode;}public static void main(String[] args) {// TODO Auto-generated method stubtry {int[] ary = {3,4,5,7,1,40,10,50};Node head = new Node(30);for (int i = 0; i < ary.length; i++) {Node.addTail(head, new Node(ary[i]));}Node.getTail(head).next = Node.getNode(head, 0);if (hasCircle(head)) {Node meetNode = getMeetNode(head);int lenght = getLengthOfCircle(meetNode);Node start = getStartOfCircle(head, meetNode);System.out.println("length:"+lenght);System.out.println("StartNode:"+start.value);}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}
}

时间: 2024-08-28 01:22:49

链表判环问题的相关文章

Leetcode Happy Number 弗洛伊德判环解循环

今天先谈下弗洛伊德判环,弗洛伊德判环原来是在一个圈内有两人跑步,同时起跑,一人的速度是另一人的两倍,则那个人能在下一圈追上另一个人,弗洛伊德判环能解数字会循环出现的题,比如说判断一个链表是不是循环链表. Leetcode Happy Number 就是这样一道简单的题,实现方法有很多,但是弗洛伊德判环是比较简单,同时效率也是较高的那种. class Solution { public: int change(int n){ int ans = 0; for ( ; n!=0 ; ans+= (n

HDU 5154 Harry and Magical Computer 有向图判环

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5154 题解: 有向图判环. 1.用dfs,正在访问的节点标记为-1,已经访问过的节点标记为1,没有访问过的节点标记为0,如果访问到-1的节点说明说有环. 1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 using namespace std; 6 t

HDOJ 5154 Harry and Magical Computer floyd判环

floyd判环 Harry and Magical Computer Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1005    Accepted Submission(s): 404 Problem Description In reward of being yearly outstanding magic student, H

《编程之美》3.6判断链表是否相交之扩展:链表找环方法证明

先看看原题:<编程之美>3.6编程判断两个链表是否相交,原题假设两个链表不带环. 为了防止剧透使得没看过原题目的读者丧失思考的乐趣,我把最好的解法隐藏起来.由于这个问题本身的解答并不是本文的重点,扩展问题也采用这种形式呈现. 注:位于(*)符号之间的文字出自于:http://blog.csdn.net/v_july_v/article/details/6447013,作者v_JULY_v. 用指针p1.p2分别指向两个链表头,不断后移:最后到达各自表尾时,若p1==p2,那么两个链表必相交 用

单链表的环入口,环大小,解环

1.单链表是否有环 使用快慢指针,都从head出发,慢指针一次一步,快指针一次两步,如果两个指针相遇,说明链表有环,否则,快指针为null或其next为null,到达末尾节点 function hasCircle(head){ var slow = head, fast = head; while(fast && fast.next){ slow = slow.next; fast = fast.next.next; if(slow == fast){ break; } } return

POJ 2240 Arbitrage (spfa判环)

Arbitrage Arbitrage is the use of discrepancies in currency exchange rates to transform one unit of a currency into more than one unit of the same currency. For example, suppose that 1 US Dollar buys 0.5 British pound, 1 British pound buys 10.0 Frenc

poj2240 Arbitrage (spfa判环)

Arbitrage Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10997   Accepted: 4622 Description Arbitrage is the use of discrepancies in currency exchange rates to transform one unit of a currency into more than one unit of the same currenc

hdu 4324 Triangle LOVE(拓扑判环)

Triangle LOVE Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Total Submission(s): 3603    Accepted Submission(s): 1416 Problem Description Recently, scientists find that there is love between any of two people. Fo

HDUOJ--4888--Redraw Beautiful Drawings【isap】网络流+判环

链接:http://acm.hdu.edu.cn/showproblem.php?pid=4888 题意:一个矩阵,限定每行行和.列和,每个格子数字不超过k,问矩阵是否存在,如存在判断有单解还是多解. 思路:之前多校的题目,那时候还不会网络流,现在A掉了,矩阵的建图模型,判断网络流是否可行只要判断最大流是否等于总行和或总列和即可,判环是看的别人的解题报告,方法是使用dfs查找残余网络中是否有还存在容量的弧形成了环,如果有,说明可以通过这个环改变容量网络内部的增广路方式,而源汇的流量是不会变的,就