A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 满兴旺 中级黑马   /  2014-5-4 17:59  /  1189 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

怎么用java实现循环链表??

4 个回复

倒序浏览
  1. 设有n个人依围成一圈,从第1个人开始报数,数到第m个人出列,然后从出列的下一个人开始报数,数到第m个人又出列,…,如此反复到所有的人全部出列为止。设n个人的编号分别为1,2,…,n,打印出出列的顺序.

  2.     思路:用JAVA实现循环链表来解决。

  3.    /*
  4.   * @author    LuoRUI

  5. * @version 1.00 2008/10/25
  6. */

  7.     class  node            //节点类
  8. {
  9.    int  no ;          //序列
  10.    node next;         //下一个节点

  11.   public node(int no) {
  12.         
  13.         this(no, null);
  14.     }

  15.   public node(int no,node next)   //构造方法
  16. {
  17.    this.no=no;
  18.    this.next=next;
  19. }
  20.    public int getItem(){        
  21.          return no;
  22.         }
  23.         
  24.    public void setNext(node next){
  25.            this.next = next;
  26.         }
  27.         
  28.         public node getNext(){
  29.                 return next;
  30.         }

  31. }


  32. public class linkedlist
  33. {
  34. private node head,tail;      // 头指针,尾指针
  35. int size;
  36.             
  37.    
  38.     public linkedlist()          //构造方法,建一个空链表
  39. {  size=0;
  40.        head=tail=null;
  41. }
  42.     public void addhead(int i)   
  43. {
  44.   head=new node(i,head);

  45.         if (tail == null)
  46.             tail = head;
  47.   size++;
  48.     }

  49.    public void addtail(int i)   
  50. {
  51.   tail.next = new node(i);   
  52.         tail = tail.next;
  53.   tail.next=head;
  54.         size++;
  55.     }

  56.   
  57.       
  58.    public static void main(String[] args)
  59. {
  60.   int n=Integer.parseInt(args[0]);  //n为节点个数,由string数组args输入
  61.   int m=Integer.parseInt(args[1]);  //m为报几个数
  62.   linkedlist LL=new linkedlist();
  63.    
  64.   LL.addhead(1);

  65.   for (int i=2; i<n+1;i++ )         //构造循环链表
  66.   {
  67.            LL.addtail(i);
  68.   }

  69.           node temp =LL.head;
  70.          while (LL.size!=0)
  71.          {
  72.            for (int i=0;i<m-2 ; i++)
  73.         
  74.          temp=temp.next;
  75.         System.out.print(temp.getNext().getItem()+"->");         
  76.      
  77.         temp.setNext(temp.getNext().getNext());
  78.             temp=temp.next;
  79.   LL.size--;
  80.          }

  81. }
  82. }



  83. 结果输出:

  84. D:/code>java linkedlist 8 3
  85. 3->6->1->5->2->8->4->7->


  86. 韩顺平老师里面有  java从入门到精通 11讲 你去看看
复制代码

评分

参与人数 1技术分 +1 收起 理由
SyouRai_Tsk + 1

查看全部评分

回复 使用道具 举报 1 0
韩顺平老师里面有  java从入门到精通 11讲 你去看看
回复 使用道具 举报 1 0
路过,学习
回复 使用道具 举报
学习java比较深的话 可以看看集合框架的源代码 里面都是用各种链表
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马