当前位置: 移动技术网 > IT编程>开发语言>c# > C#定义并实现单链表实例解析

C#定义并实现单链表实例解析

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文以实例详细描述了c#定义并实现单链表的过程及原理。一般来说c#定义并实现单链表,代码包括构成链表的结点定义、用变量来实现表头、清空整个链表 、链表复位,使第一个结点成为当前结点、判断链表是否为空、判断当前结点是否为最后一个结点、返回当前结点的下一个结点的值,并使其成为当前结点、将当前结点移出链表,下一个结点成为当前结点等内容。

具体实现代码如下所示:

using system;
using system.io;
// 构成链表的结点定义 
public class node 
{
 public object data;
 public node next;
 public node( object d ) 
 {
 data = d;
 next = null;
 }
}
public class list 
{
 // 用变量来实现表头
 private node head = null;
 private node tail = null;
 private node pointer = null;
 private int length = 0;
 //清空整个链表 
 public void deleteall( ) 
 {
 head = null;
 tail = null;
 pointer = null;
 length = 0;
 }
 //链表复位,使第一个结点 成为当前结点
 public void reset( ) 
 {
 pointer = null;
 }
 //判断链表是否为空
 public bool isempty( ) 
 {
 return (length == 0);
 }
 //判断当前结点是否 为最后一个结点
 public bool isend( ) 
 {
 if (length == 0)
  throw new system.exception( );
 else if (length == 1)
  return true;
 else
  return (cursor( ) == tail);
 }
 //返回当前结点的下一个结点的值, 并使其成为当前结点
 public object nextnode( ) 
 {
 if (length == 1)
  throw new system.exception( );
 else if (length == 0)
  throw new system.exception( );
 else 
 {
  node temp = cursor();
  pointer = temp;
  if (temp != tail)
  return (temp.next.data);
  else
  throw new system.exception( );
 }
 }
 //返回当前结点的值
 public object currentnode( ) 
 {
 node temp = cursor( );
 return temp.data;
 }
 //在当前结点前插入一个结点, 并使其成为当前结点
 public void insert( object d ) 
 {
 node e = new node( d );
 if (length == 0) 
 {
  tail = e;
  head = e;
 } 
 else 
 {
  node temp = cursor( );
  e.next = temp;
  if (pointer == null)
  head = e;
  else
  pointer.next = e;
 }
 length++;
 }
 //返回链表的大小
 public int size( ) 
 {
 return length;
 }
 //将当前结点移出链表,下一个结点成为当前结点
 //如果移出的结点是最后一个结点,则第一个结点成为当前结点
 public object remove( ) 
 {
 object temp;
 if (length == 0)
  throw new system.exception( );
 else if (length == 1) 
 {
  temp = head.data;
  deleteall( );
 } 
 else 
 {
  node cur = cursor( );
  temp = cur.data;
  if (cur == head)
  head = cur.next;
  else if (cur == tail) 
  {
  pointer.next = null;
  tail = pointer;
  reset( );
  } 
  else
  pointer.next = cur.next;
  length--;
 }
 return temp;
 }
 //返回当前结点的指针
 private node cursor( ) 
 {
 if (head == null)
  throw new system.exception( );
 else if (pointer == null)
  return head;
 else
  return pointer.next;
 }
 //链表的简单应用举例
 public static void main( ) 
 {
 list a = new list();
 for (int i = 1; i <= 10; i++)
  a.insert( new intptr(i));
 console.writeline(a.currentnode( ));
 while (!a.isend( ))
  console.writeline(a.nextnode( ));
 a.reset();
 while (!a.isend( )) 
 {
  a.remove( );
 }
 a.remove( );
 a.reset( );
 if (a.isempty( ))
  console.writeline("there is no node in list!");
 console.writeline("you can press return to quit!");
 try 
 {
  // 确保用户看清程序运行结果
  console.read( );
 } 
 catch (ioexception e) 
 {
 }
 }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网