首页 > 代码库 > 单链表的C#实现
单链表的C#实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithm {
class MyListNode<T> {
public T Key { get; set; }
public MyListNode<T> Next { get; set; }
public MyListNode(T k) {
Key = k;
}
}
class MyList<T> {
private MyListNode<T> head;
public MyListNode<T> Head {
get {return head;}
set {head = value;}
}
public MyList(){
head = null;
}
public void Walk(MyListNode<T> headNode,Action<T> act) {
MyListNode<T> node = headNode;
while (node != null) {
act(node.Key);
node = node.Next;
}
}
public MyListNode<T> Add(T key) {
MyListNode<T> newNode = new MyListNode<T>(key);
if (head == null) {
head = newNode;
} else {
MyListNode<T> node = head;
while (node.Next != null) {
node = node.Next;
}
node.Next = newNode;
}
return newNode;
}
public void Add(T[] keys) {
foreach (var i in keys) {
Add(i);
}
}
public void Delete(MyListNode<T> node) {
node.Key = node.Next.Key;
node.Next = node.Next.Next;
}
//翻转
public MyListNode<T> Rverse(MyListNode<T> head) {
if (head == null || head.Next == null)
return head;
MyListNode<T> nextNode = head.Next;
MyListNode<T> newHead = Rverse(nextNode);
nextNode.Next = head;
head.Next = null;
return newHead;
}
//寻找中间节点
public MyListNode<T> FindMid(MyListNode<T> head) {
MyListNode<T> fast = head;
MyListNode<T> slow = head;
while (fast != null) {
if (fast.Next != null) {
fast = fast.Next.Next;
} else {
break;
}
slow = slow.Next;
}
return slow;
}
}
}
null
单链表的C#实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。