7,环形链表

实现思路:

1)first指针,指向第一个节点。辅助指针指向当前节点

2)每创建新节点,next都重新指向第一个节点,形成环

C#实现代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace 数据结构
 6 {
 7     public class CircleLinked
 8     {
 9         //创建头指针
10         private Node First {get;set;}
11         //创建环形链表
12         public void Add(int nums)
13         {
14             if (nums < 1)
15             {
16                 Console.WriteLine("至少需要一个节点");
17                 return;
18             }
19             //创建辅助指针
20             Node curNode = null;
21             for (int n = 1; n <= nums; n++)
22             {
23                 Node node=new Node(n);
24                 if (n == 1)
25                 {
26                     //First和curNode指针指向第一节点
27                     First = node;
28                     curNode = First;
29                     //指向自己形成环路
30                     curNode.Next = First;
31                     continue;
32                 }
33                 //上一节点断开环路,Next指向下一节点
34                 curNode.Next = node;
35                 //curNode指针移指向下一节点
36                 curNode = node;
37                 //指向第一个节点,形成环路
38                 curNode.Next = First;
39             }
40         }
41         
42         //打印环形链表
43         public void Scan()
44         {
45             if (First == null)
46             {
47                 Console.WriteLine("空链表");
48             }
49             //创建辅助指针
50             var curNode = First;
51             while (true)
52             {
53                 Console.Write($"{curNode.No}\t");
54                 //如果Next地址三First说明已经到最后一个
55                 if (curNode.Next == First)
56                 {
57                     break;
58                 }
59                 curNode = curNode.Next;
60             }
61         }
62 
63 
64         public class Node
65         {
66             public int No { get; set; }
67             public Node Next { get; set; }
68             public Node(int no)
69             {
70                 this.No = no;
71             }
72         }
73     }
74 
75     public class Josephus
76     {
77         public static void Main(string[] args)
78         {
79             var circle =new CircleLinked();
80             Console.WriteLine("加入41个人");
81             circle.Add(41);
82             circle.Scan();
83         }
84     }
85 }

posted @ 2020-04-14 22:29  小橘·Huang  阅读(153)  评论(0编辑  收藏  举报