VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之C#教程之数据结构----链表的增和插入

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

链表方便于增和删

链表的增和插入

因为链表没有下标所以增的话需要一个类似于标签的node来指示!

代码一:(构造函数,初始化)

复制代码
 1 namespace 链表
 2 {
 3     public class Node
 4     {
 5         public int Data;
 6         //这个就是地址
 7         public Node Next;
 8         // 构造函数目的就是初始化
 9         public Node()
10         {
11             Data = default(int);
12             Next = null;
13         }       
14         public Node(int  value)
15         {
16             Data = value;
17             Next = null;
18         }
19     }
20 }
复制代码

代码二:(主要的实现方法!!!重点)

复制代码
 1 using System;
 2 namespace 链表
 3 {
 4     //链表都是有头部节点的 简称为头结点 头结点不参与运算
 5     public class LinkList
 6     {
 7         private Node _head;
 8         private int _count;
 9         public LinkList()
10         {
11             _head = new Node();
12             _count = 0;
13         }
14         public void AddItem(Node newNode)
15         {
16             //找到头结点
17             Node tmpNode = _head;
18             //循环找到最后结点
19             while (tmpNode.Next != null)
20             {
21                 //一直下移
22                 tmpNode = tmpNode.Next;
23             }
24               //将最后结点和即将插入的结点链接
25             tmpNode.Next = newNode;
26             //个数++
27             _count++;
28         }
29         public int GetLength()
30         {
31             return _count;
32         }
33         public void Insert(int index, Node newNode)
34         { 
35             if (index < 0 || index > _count)
36             {
37                 Console.WriteLine("Over");
38                 return;
39             }
40             Node tmpNode = _head;
41             for (int i = 0; i < index; i++)
42             {
43                 tmpNode = tmpNode.Next;
44             }
45             newNode.Next = tmpNode.Next;
46             tmpNode.Next = newNode;
47             _count++;
48         }
49     }
50 }
复制代码

 

代码三:(实现)

复制代码
 1 using System;
 2 namespace 链表
 3 {
 4     internal class Program
 5     {
 6         public static void Main(string[] args)
 7         {
 8             LinkList linkList = new LinkList();
 9             linkList.AddItem(new Node(1));
10             linkList.AddItem(new Node(2));
11             linkList.AddItem(new Node(3));
12             linkList.AddItem(new Node(4));
13             linkList.AddItem(new Node(5));
14             linkList.Insert(1,new Node(1000));
15             Console.WriteLine(linkList.GetLength());
16             Console.Read();
17         }
18     }
19 }
复制代码

输出:6

相关教程