class ArrayList
{
private const int MAX_LENGTH = 20;
private int[] _array = new int[MAX_LENGTH];
private int _index = -1;
public ArrayList()
{
}
public void Revert()
{
int low = 0;
int high = _index;
while(low<=high)
{
Swap(low, high);
low++;
high--;
}
}
private void Swap(int i,int j)
{
int temp = _array[i];
_array[i] = _array[j];
_array[j] = temp;
}
public void Insert(int val)
{
if(IsFull())
{
throw new Exception("已满");
}
else
{
_array[++_index] = val;
}
}
public void Show()
{
for(int i=0;i<=_index;i++)
{
Console.WriteLine(_array[i]);
}
}
public bool IsFull()
{
return _index == MAX_LENGTH - 1;
}
}
以上是逆转数组线性表
逆转链表,有3种方法,不说了,看代码吧
class LinkedList
{
private LinkNode predix = new LinkNode(){next = null};
public void Insert(int val)
{
LinkNode current = predix;
while (current.next != null)
{
current = current.next;
}
current.next = new LinkNode(){value = val,next = null};
}
public void Show()
{
LinkNode current = predix.next;
while (current != null)
{
Console.WriteLine(current.value);
current = current.next;
}
}
//栈
public void Revert1()
{
Stack<LinkNode> nodes = new Stack<LinkNode>();
LinkNode current = predix.next;
while(current != null)
{
nodes.Push(current);
current = current.next;
}
LinkNode tail = predix;
while (nodes.Count!=0)
{
tail.next = nodes.Pop();
tail = tail.next;
}
tail.next = null;
}
//递归
public void Revert2()
{
LinkNode revertHead = null;
//经过这一个递归,头结点后面的节点之间的指向逆序。
Revert(predix.next,ref revertHead);
//改变原来第一个节点的next,使其指向空
if(predix.next != null)
{
predix.next.next = null;
}
//并用predix指向逆序后的头
predix.next = revertHead;
}
private void Revert(LinkNode node,ref LinkNode revertHead)
{
if(node == null)
return;
else
{
LinkNode nextNode = node.next;
revertHead = node;//这地方有点猥琐,其实想办法更新revertHead就可以,用成员变量(field)就可以实现,但是我不乐意用
Revert(node.next,ref revertHead);//传的revertHead,让在更深层次的递归调用更改它
if(nextNode!=null)//最后一个节点特殊点
nextNode.next = node;
}
}
//引用方法
public void Revert3()
{
LinkNode guard;
LinkNode current = predix.next;
LinkNode pre = null;
while (current != null)
{
guard = current.next;//先保存后面的节点,防止current的next指向前面后面的找不到了
current.next = pre;
pre = current;
current = guard;
}
predix.next = pre;
}
}
class LinkNode
{
public int value;
public LinkNode next;
}