zoukankan      html  css  js  c++  java
  • csinglelink

    package csinglelink;

    class Node {

    int iData;
    Node Child;

    public Node() {
    }

    public Node(int i) {
    iData = i;
    Child = null;
    }
    }

    class SingleLink {

    Node head = null;

    public SingleLink() {
    }
    //展示链表
    public void display() {
    Node current = head;
    if (current == null) {
    System.out.println("链表空 ");
    return;
    }
    while (current!= null) {
    System.out.print(current.iData + " ");
    current = current.Child;
    }
    }
    public void display(int i) {
    Node current = head;
    if (current == null) {
    System.out.println("链表空 ");
    return;
    }
    for(int j=0;j<i;j++)
    {
    System.out.print(current.iData+" ");
    current=current.Child;
    }
    }
    //构造链表
    public SingleLink(int slong) {

    for (int i = 0; i <slong; i++) {
    Node nd = new Node(i);
    if (head == null) {
    head = nd;
    } else {
    Node current = head;
    while (current.Child != null) {
    current = current.Child;
    }
    current.Child = nd;
    }
    }
    display();
    }
    //构造环,即尾部指向其中;
    public void makeC(int data){
    Node circle=new Node();
    Node tail=new Node();
    Node current=head;


    if(current==null){System.out.println("链表为空,");return;}
    //寻找环点;
    while(current!=null)
    {
    if(current.iData==data){circle=current;System.out.print("已找到\n");break;}
    current=current.Child;
    }
    System.out.println("找到为:"+circle.iData);
    current=head;
    while(current.Child!=null)
    {
    current=current.Child;
    }
    tail=current;
    //构建有环链表
    tail.Child=circle;
    display(15);

    }
    //判断是否有环;
    //判断方法为,构建两个单链表不可能相等的结点A,B,不断移动,AB指向同一个结点,则有环。
    //用=判断是否指向同一个,终止条件为B.child为null;
    public boolean isc()
    {
    if(head==null||head.Child==null){System.out.println("链表为空或者那啥" );return false;}
    Node currenta=head;
    Node currentb=head.Child;
    while(currentb.Child.Child!=null){
    currentb=currentb.Child.Child;
    currenta=currenta.Child;
    if(currenta==currentb){System.out.println("\n链表有环" );return true;}
    }
    return true;
    }
    }

    /**
    *
    * @author Administrator
    */
    public class CSingleLink {

    /**
    * @param args the command line arguments 有环链表
    */
    public static void main(String[] args) {
    // TODO code application logic here
    SingleLink sl = new SingleLink(10);
    sl.makeC(4);
    sl.isc();
    }
    }

  • 相关阅读:
    Optional类的基本使用(没怎么看)
    443. String Compression字符串压缩
    520. Detect Capital判断单词有效性
    521. Longest Uncommon Subsequence I 最长不同子数组
    459. Repeated Substring Pattern 判断数组是否由重复单元构成
    686. Repeated String Match 字符串重复后的子字符串查找
    696. Count Binary Substrings统计配对的01个数
    58. Length of Last Word最后一个单词的长度
    680. Valid Palindrome II 对称字符串-可删字母版本
    125. Valid Palindrome判断有效的有符号的回文串
  • 原文地址:https://www.cnblogs.com/xiekai/p/3493346.html
Copyright © 2011-2022 走看看